Matlab Engineer Tabular Features
MathWorksOfficialCreated by MathWorks
- Skill
- Workflow
- Data and AI
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a rigorous, data-driven workflow for feature engineering and selection in MATLAB. It manages the entire process from initial data intake and screening to feature pool generation, consensus-based selection, and diagnostic assessment. Designed for single-response supervised learning, it handles both tabular and non-tabular data by routing complex extractions to domain-specific skills. The workflow emphasizes train-test discipline, ensuring that feature generation and selection are performed on training data while maintaining a held-out set for unbiased evaluation. It concludes by delivering a self-contained inference script that allows users to reproduce the selected feature set on new data.
What it does
- Screens raw data to remove degenerate or constant predictors.
- Generates a candidate feature pool using either SMLT or domain-specific extractors.
- Performs consensus-based feature selection using a ranker panel and elbow-cut logic.
- Assesses feature set quality and stability through performance metrics and resampling.
- Produces a standalone MATLAB inference script for applying the selected features to new data.
- Generates comprehensive reports on the selection process and model-free feature quality.
When to use it
- When you need to engineer and select the best predictors for a single-response classification or regression task.
- When you require a structured, reproducible selection process rather than ad-hoc feature picking.
- When working with non-tabular data that requires specialized extraction before feature selection.
- When you need a reliable, self-contained script to apply your feature engineering pipeline to future datasets.
Advantages
- Enforces strict train-test discipline to prevent data leakage.
- Provides a consensus-driven approach to feature selection that reduces bias.
- Offers diagnostic tools to evaluate feature set stability and predictive performance.
- Delivers a portable inference script that encapsulates the entire transformation logic.
Usage examples
- “I have a table of sensor data and want to select the best features for a regression model.”
- The agent will initiate the intake phase, confirm your output directory, and guide you through the feature engineering and selection workflow.
- “Can you help me select features for my classification task and check if they are stable?”
- The agent will perform the selection and then offer to run stability gates to see if the same features are chosen across resampled data.
Install
8 of its files are not mirrored here, so install it from its source:
https://github.com/matlab/matlab-agentic-toolkit/tree/2a7f215e965597acf6ed495beb9e7b8aff45a3be/skills-catalog/ai-and-statistics/matlab-engineer-tabular-features
Documentation by MathWorks
Engineer Tabular Features
A lean, functional pipeline: intake → feature pool → select → assess →
deliver → report. There is no shared context object — each phase is a direct
call to leaf utilities in scripts/, and the reference file for each phase
carries the detail. Your value is the structured, data-driven process and,
above all, the consensus selection at its center — not an ad-hoc answer.
This skill bundles the workflow in references/ (per-phase detail read on demand)
and scripts/ (the computation and plotting utilities). Do not invoke files in
references/ as separate skills — they are loaded only via the Read tool when
the phase that needs them runs. The per-phase files call the pipeline's leaf helpers
for you; if you ever need a helper's signature,
references/internal-helpers.md documents each one's
inputs, outputs, and an example call — so you never open a helper's source.
When to Use
Engineering or selecting the best predictors for single-response supervised classification or regression on a plain in-memory
table.You want a structured, data-driven selection — a ranker panel, a consensus vote, and an elbow cut — rather than an ad-hoc hand-picked feature set.
The data is non-tabular (signals, images, battery/machinery telemetry): this skill routes extraction to the matching domain skill, then engineers, selects, assesses, and delivers on the resulting table (see references/domain-routing.md).
When NOT to Use
Multi-response problems — this skill is single-response only.
Model training, tuning, or deployment — it prepares features and stops. Hand the delivered table to a model-training/classification workflow to fit and compare models.
Raw data acquisition. And for the extraction step on non-tabular data, the actual feature computation belongs to the matching domain extraction skill — this skill orchestrates that handoff (see references/domain-routing.md), it does not re-implement it.
Requires the Statistics and Machine Learning Toolbox (SMLT) —
gencfeatures/genrfeatures build the pool and the ranker/assessment utilities
are SMLT-based. MATLAB Report Generator is optional (enables the PDF report;
markdown is always produced).
Running MATLAB
Run all MATLAB through the MATLAB MCP server (mcp__matlab__evaluate_matlab_code,
or mcp__matlab__run_matlab_file for scripts). Set project_path to this skill's
scripts/ directory so the utilities resolve on the current working folder
without any addpath calls. Every utility is a leaf function called directly —
there is no initialization step and no context object to construct. Validate any
code you author with mcp__matlab__check_matlab_code before running it.
Start each dataset from scratch — but use the live workspace within a run. The
MCP session is stateful, so a run's intermediates should live in the workspace: set
RawTbl, Splits, FullEng, SelectedNames, Baseline, etc. once and pass them
phase-to-phase. Do not round-trip them through save/load .mat files (noise,
risks stale reads) and do not addpath. Across different datasets/runs, carry
nothing — begin each analysis by setting every variable afresh.
Communication style while running this skill
Talk to the user about their data and results, not the skill's plumbing.
Everything under references/ and scripts/ is internal. Rule of thumb: if a
sentence would only make sense to someone who has read this skill's source files,
don't say it.
Never name internal files, helpers, or phase/gating mechanics.
runConsensusSelection,GenInfo.BinaryReliant, "the redundancy dimension", etc. are internal — give the outcome ("these features duplicate each other, so I'm keeping the strongest"), not the mechanism. Name an internal only when it is a problem the user can act on. Read reference files silently.Use plain words for each check. The three assessment reads: performance → whether the new features improve predictions (a held-out estimate, or a cross-validated mean ± std); fixed-pool stability → whether the same features get picked when rows are resampled; generation stability → whether the same features get built and picked when the whole pipeline re-runs on resampled rows. Say "the ranking step" not "the borda voter"; "reliably re-selected" not "consensus core".
Don't narrate uncertainty or mid-flight course-corrections — settle how a function is called silently, then report only the outcome. Surface a difficulty only when the user must decide on it.
Announce cost before long work, one sentence — pool size before selection, expected time before a K-fold, and before either stability gate (both re-run selection many times; the generation gate also re-builds the pool each time). And surface user-facing questions verbatim where a phase specifies one (output directory, wide-input, domain routing).
Report what was dropped at every phase (screened predictors, excluded WoE columns, skipped rankers) — a silent shrink reads as data loss. But selection evaluates the pool, it doesn't necessarily shrink it — never call it a reduction.
Output directory — REQUIRED, HARD HALT
Deliverables are written to disk. Always confirm the output directory with the user before writing anything. Do not assume the working directory, do not create one silently.
The pipeline
Follow the phases in order. Each links to its reference; read the reference before executing the phase.
1. Intake — references/intake.md
Ask before running any code. Intake is a required conversation, not a
default-fill. Confirm every run parameter with the user before proceeding past
the screen — data source, response, dataset name, output directory (hard-halt),
domain description, separate-test-set, model family (+ lens if agnostic),
evaluation strategy, report opt-out — asked one at a time, in the order pinned in
intake.md §1 (never dump the whole list in one message).
Every item must be asked; offer a default where one exists, but confirm rather than
assume — when the opening request implies an answer, state what you inferred and
have the user confirm it. Two are
non-negotiable — do not proceed without an explicit answer:
Output directory — the disk-write hard-halt (see above).
Domain description — the sole input to domain routing. Ask what the data is and where it came from; route to a domain extractor if one fits, else the generic path. Never infer the domain from column names or fall through to generic generation on silence. Verbatim prompt in intake.md.
Then assemble the data into one plain table, briefly confirm what was
loaded (shape, response, problem type), and screen degenerate predictors. A
timetable/tall/gpuArray/datastore isn't a dead end — it's a signal to run a
tabularizing step first (often a domain skill, see
domain-routing.md) and then re-enter intake with
the resulting table; only halt if no tabular path exists.
[ScreenedTbl, ScreenInfo] = screenPredictors(RawTbl, Response); % or (X, y)screenPredictors handles the polymorphic response (a name already in the table,
or a separately-supplied vector/table it concatenates) and drops constant and
near-empty predictors. Then profile, reserve the user's untouched slice, and split:
Profile = profileForSplit(ScreenedTbl, ScreenInfo.ResponseVar);
[WorkingIdx, UserHeldOutIdx, ReserveInfo] = reserveHoldoutForUser( ...
ScreenedTbl, Profile.ProblemType, ScreenInfo.ResponseVar, ReserveForUser = HasNoSeparateTest);
[Splits, SplitDecision] = splitStrategy(ScreenedTbl, Profile.ProblemType, ...
ScreenInfo.ResponseVar, Subset = WorkingIdx, EvaluationStrategy = EvaluationStrategy);reserveHoldoutForUser sets aside an untouched slice for the user's own testing
when they have no separate test set (default 20%, user-settable via HoldoutFraction;
else nothing); the rest is the working data all phases run on. When a carve
happens, materialize the slice as the table variable's name + _test from the original
rows and narrate the split in plain words (fraction, row counts, and method —
stratified/random — from ReserveInfo); see intake.md. splitStrategy then sets
Splits.TrainIdx/.TestIdx over the working rows — a train/test split under
holdout, or all working rows with empty TestIdx under cross_validated.
Generation and selection run on TrainIdx only.
2. Feature pool — references/feature-pool.md
Produce the candidate pool. First check whether a domain skill fits the data (references/domain-routing.md); otherwise use the default SMLT path:
Opts.TargetModel = TargetModel; Opts.Standardization = "auto";
OptArgs = namedargs2cell(Opts);
TrainIdx = Splits.TrainIdx; TestIdx = Splits.TestIdx;
TrainTbl = ScreenedTbl(TrainIdx, :); % fit generation on train rows only
[~, Transformer, GenInfo] = generateFeatures(TrainTbl, Response, ProblemType, OptArgs{:});
Recipe = Transformer; % SMLT recipe (domain path: the captured struct)
FullEng = transformFeatures(Recipe, ScreenedTbl); % engineered pool over ALL rows
FullEng.(Response) = ScreenedTbl.(Response); % transformFeatures returns predictors onlyGenerate-only (external consensus does the cutting). Mind the wide-input guard
(generateFeatures:tooManyPredictors) — hold the wide-input conversation and
re-call with Opts.NumFeatures set. FullEng is the canonical pool: engineered
over all rows with the response re-attached, train-fit so the held-out rows
stay leakage-clean. On the domain path the captured table already spans all
rows — use it as FullEng directly. Whichever path runs, downstream reads only
the pool contract (Recipe, describeFeatures, transformFeatures) — never
the producer. Announce GenInfo.PoolSize.
Set OriginalData/OriginalPredVars here — the baseline's "original" reference is
path-dependent (raw columns when they exist, else the full pool). assess.md §1 pins the rule.
3. Select — references/select.md
The heart of the skill. One call runs the ranker panel, the consensus vote, and the elbow cut:
[SelectedNames, VoteTable, PanelInfo] = runConsensusSelection( ...
FullEng(TrainIdx, :), Response, ProblemType, ExcludeFeatures = GenInfo.BinaryReliant, ...
TargetModel = TargetModel);Selection runs on the training rows only — slice FullEng(TrainIdx,:); the
held-out rows never enter ranking. TargetModel gates the ranker panel: a declared
family runs its own embedded probe (linear→lasso, tree_ensemble→oob,
kernel_distance→nca) plus the two model-agnostic rankers; agnostic (the default)
keeps the full five-ranker panel. Report PanelInfo.Reasoning. Build a
plotSelectionConsensus figure only when the report is on (GenerateReport) —
every figure is a report input, so a report opt-out skips all plot calls.
The score elbow alone sets the count (see select.md); when the scores decline too gradually to show a knee the full pool is kept — report a keep-all as "the candidates are comparably useful," not as a failure to select.
4. Assess — references/assess.md
Diagnostic only; never revises the delivered set. The performance read follows the evaluation strategy chosen at intake:
Quality = featureSetQuality(ScreenedTbl, FullEng, TrainIdx, Response, ...
OriginalPredVars, SelectedNames, ProblemType); % model-free, always
if Splits.Strategy == "holdout" % point estimate on the held slice
Baseline = baselineComparison(ScreenedTbl, FullEng, TrainIdx, TestIdx, Response, ...
OriginalPredVars, SelectedNames, ProblemType, TargetModel = TargetModel, InternalCV = false);
else % cross_validated: folds ARE the estimate
KFold = assessKFold(ScreenedTbl(TrainIdx, :), Response, ProblemType, CVP, TargetModel = TargetModel);
end
% Stability — two independent opt-in gates, both default OFF (assess.md §3):
rng(0, "twister");
SelStab = assessSelectionStability(StabEng, Response, ProblemType, ... % Gate 1 (fixed pool)
ExcludeFeatures = StabExclude, TargetModel = TargetModel, MaxRows = RowBudget);
GenStab = assessGenerationStability(RawTrainTbl, Response, ProblemType, ... % Gate 2 (pool regenerated)
TargetModel = TargetModel, MaxRows = RowBudget);Pass a row budget to both gates as MaxRows only when the user named one
("~1000 patients is fine" → MaxRows = 1000) to keep the audit affordable; else
omit it (default 3000) — don't pass an empty value.
Quality (model-free representation quality) and the strategy's performance read
are unconditional: under holdout, baselineComparison scores the held
TestIdx as a point estimate (InternalCV = false, no error bars); under
cross_validated (TestIdx empty), assessKFold is the headline (regenerates per
fold, reports mean ± std, performance-only) — skip baselineComparison.
Stability is two independent opt-in gates, both default OFF (see
assess.md §3): Gate 1 SelStab (re-selects on a fixed
pool) and Gate 2 GenStab (also regenerates the pool per subsample; needs a
re-runnable fitter — SMLT by default, a domain path needs Recipe.Fit, §3c). Both
are computationally expensive — each re-runs the consensus selection M times, and
Gate 2 adds a full regeneration on top — so both stay off unless asked for. Both
grade the procedure; neither revises the delivered set. Offer the choice, don't
default them on, and announce the cost — ask "Want a stability check — would the
same features get picked if the data were resampled? It re-runs selection many times
so it takes a while; a deeper version also re-builds the features each time, costing
more again." and run only what the user opts into. When neither is requested, add
neither and set Results.StabilitySkipped = true (report says "not requested"). Skip
a requested gate automatically with that flag when the pool has < 2 features or < 2
subsamples are possible.
5. Deliver — references/deliver.md
Write the artifacts to the confirmed output directory:
[ScriptPath, MatPath] = writeInferenceScript(Recipe, SelectedNames, OutputDir, ...
DatasetName = DatasetName, ResponseVar = ResponseVar);
SelectedTbl = selectFeatures(Recipe, RawTbl, SelectedNames); % in-workspace CHECK only — do NOT write to diskThe recipe is the inference recipe — fe_transform_<dataset>.m +
its companion .mat reproduce the exact selected set on new raw data with one
call. writeInferenceScript is generator-agnostic (SMLT FeatureTransformer or a
Kind=="domain" recipe) and inlines its logic, so the deliverable stands alone.
SelectedTbl is only a verification value — never write the feature table to
disk (features_<dataset>.mat/.csv); the inference script regenerates it on
demand, so a materialized dump is redundant. Write the figures' fig_*.svg
alongside only when the report is on; under a report opt-out the inference
script + state are the whole deliverable.
Also save the full Results struct unconditionally — every run result at full
resolution, so nothing a plot or a truncated table only previews is lost:
ResultsMatPath = saveResults(Results, OutputDir, DatasetName = DatasetName);This fe_results_<dataset>.mat ships even on a report opt-out (assemble Results
first — see report.md). Tell the user it exists, and that
the same data is live in the Results workspace variable this session.
6. Report — references/report.md
Optional (opt-out, default on) — run only if the user kept the report at intake
(GenerateReport == true), the same flag that gates every figure in
Select/Assess/Deliver. When run, assemble the plain Results struct from every
prior phase and emit:
MdPath = generateFeatureReport(Results, OutputDir); % always
if hasReportGenerator(); PdfPath = generateFeatureReportPdf(Results, OutputDir); end % if available7. Hand off to model training (offer, don't invoke)
This skill stops at features. If the user's ask mentioned training a model (supervised learning, classification, regression, etc.) and an installed skill covers tabular model training, name that candidate once at close-out and offer to hand off — semantic match against the injected skill list, confirm before invoking, no hardcoded skill names (same discovery rule as domain-routing.md). If nothing fits or the ask was features-only, stop silently.
Behavioral contract (all phases)
Train/test discipline — generation, selection, and all training-side statistics use the training rows only; the test rows certify the delivered artifact and are never seen before then.
Generator-agnostic downstream — after the pool phase, touch generator internals only through
describeFeatures/transformFeatures.No hidden truncation — if you cap, sample, or skip anything, say so.
Never fabricate a pool — when routing offers a choice, or the data needs a tabularizing step this skill can't perform, presenting the choice or asking ends the turn. Wait for the user before building the pool by any means (domain skill, generic path, or an extractor of your own).
Confirm outward-facing actions — writing to disk is confirmed once at intake (the output-dir hard-halt); don't write outside it.
MathWorks Coding Guidelines for any MATLAB you author (lowerCamelCase,
argumentsblocks, ≤6 in / ≤4 out,endterminators; modern APIs).
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks for a list of additional trademarks.
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.1 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md18.9 KiB
- manifest.yaml570 B
- references/assess.md16.7 KiB
- references/deliver.md13.0 KiB
- references/domain-routing.md18.1 KiB
- references/feature-pool.md10.9 KiB
- references/intake.md16.9 KiB
- references/internal-helpers.md12.2 KiB
- references/provider-protocol.md12.3 KiB
- references/report.md9.7 KiB
- references/reproduce-pool.md7.1 KiB
- references/select.md7.1 KiB
- scripts/BordaVoter.m2.3 KiB
- scripts/ConsensusVoter.m2.5 KiB
- scripts/MajorityVoter.m2.0 KiB
- scripts/RRFVoter.m1.9 KiB
- scripts/assessGenerationStability.m11.9 KiB
- scripts/assessKFold.m20.6 KiB
- scripts/assessSelectionStability.m9.8 KiB
- scripts/baselineComparison.m18.9 KiB
- scripts/buildRecipe.m8.2 KiB
- scripts/chooseNumBins.m5.0 KiB
- scripts/chooseStandardization.m4.5 KiB
- scripts/computeNSelect.m2.9 KiB
- scripts/createConsensusVoter.m2.2 KiB
- scripts/describeFeatures.m5.1 KiB
- scripts/expandBlockMap.p(opens on GitHub)Not mirrored: opens on GitHub440 B
- scripts/featureSetQuality.m12.3 KiB
- scripts/generateFeatureReport.m67.2 KiB
- scripts/generateFeatureReportPdf.m64.9 KiB
- scripts/generateFeatures.m14.6 KiB
- scripts/hasReportGenerator.m630 B
- scripts/isDomainRecipe.m1.4 KiB
- scripts/isStringEmpty.m577 B
- scripts/lambdaSequence.p(opens on GitHub)Not mirrored: opens on GitHub637 B
- scripts/lassoFeatureRanking.p(opens on GitHub)Not mirrored: opens on GitHub971 B
- scripts/macroF1Score.m931 B
- scripts/mrmrFeatureRanking.p(opens on GitHub)Not mirrored: opens on GitHub239 B
- scripts/mutualInformationPanel.p(opens on GitHub)Not mirrored: opens on GitHub1.1 KiB
- scripts/ncaFeatureRanking.p(opens on GitHub)Not mirrored: opens on GitHub464 B
- scripts/nogueiraStability.m3.8 KiB
- scripts/oobFeatureRanking.p(opens on GitHub)Not mirrored: opens on GitHub414 B
- scripts/plotSelectionConsensus.m2.7 KiB
- scripts/plotSelectionDecision.m6.3 KiB
- scripts/plotSelectionStability.m10.2 KiB
- scripts/plotValidationBaseline.m6.1 KiB
- scripts/printSummary.m18.3 KiB
- scripts/profileForSplit.m6.2 KiB
- scripts/rankAgreement.m1.3 KiB
- scripts/rankFeatures.m6.2 KiB
- scripts/reserveHoldoutForUser.m5.5 KiB
- scripts/runConsensusSelection.m9.4 KiB
- scripts/sampleSkewness.m600 B
- scripts/saveResults.m2.1 KiB
- scripts/scoreFeaturePanel.p(opens on GitHub)Not mirrored: opens on GitHub1.6 KiB
- scripts/screenPredictors.m13.3 KiB
- scripts/selectFeatures.m2.3 KiB
- scripts/splitStrategy.m5.4 KiB
- scripts/stratifiedDownsampleRows.m2.2 KiB
- scripts/stratifiedSubsampleIndices.m3.4 KiB
- scripts/transformFeatures.m6.1 KiB
- scripts/validateRecipe.m12.3 KiB
- scripts/writeInferenceScript.m10.5 KiB
scripts/assessKFold.m
function Result = assessKFold(RawTrainTbl, Response, ProblemType, CVPartition, Options)
%assessKFold K-fold PERFORMANCE read of the whole feature-engineering pipeline.
%
% Result = assessKFold(RawTrainTbl, Response, ProblemType, CVPartition) wraps
% the ENTIRE pipeline -- generate -> select -> model contrast -- in a single
% K-fold loop over the training rows and reports how the engineered recipe
% performs on held-out folds. The folds are supplied by the caller as a
% cvpartition object so the same function serves stratified, grouped, or
% time-series schemes without change; K is taken from CVPartition.NumTestSets.
%
% This partition is INNER and diagnostic: it k-folds the TRAINING block only.
% It is a different job from the outer train/val/test holdout that
% splitStrategy produces for the pipeline run itself -- do not conflate them.
% The caller builds the cvpartition (e.g. cvpartition(y, KFold=5) for a
% stratified classification scheme, or cvpartition(n, KFold=5) otherwise).
%
% The reads:
%
% PERFORMANCE (repeatability + lift). Each fold refits gencfeatures on its
% own training rows (so the engineered VALUES differ fold to fold, even
% though the feature DEFINITIONS are largely shared), re-selects, and scores
% an engineered-vs-original-vs-naive contrast on the held-out fold. Reported
% as mean +/- std across folds: how repeatable the whole recipe is, and how
% much the engineered set actually beats the raw features and a naive
% predictor. This is the honest end-to-end variance -- it includes the
% generation step, which a single holdout hides. Because this loop owns the
% performance-variance estimate, the per-fold baselineComparison runs with
% InternalCV=false (its own k-fold CV would be redundant here).
%
% REPRESENTATION-QUALITY STABILITY. Each fold's engineered set is scored by
% featureSetQuality on that fold's TRAINING rows (engineered-side only) and
% the dimensions aggregated mean +/- std across folds -- how much the recipe's
% OUTPUT quality wobbles under resampling. Distinct from the shipped set's own
% quality (featureSetQuality on all working data at delivery).
%
% This is DIAGNOSTIC ONLY. It grades the recipe's held-out performance; it
% never revises the delivered feature set.
%
% Inputs:
% RawTrainTbl - table of RAW predictors + response, TRAINING rows only (the
% final test set is held out upstream and never seen here)
% Response - (1,1) string, response variable name in RawTrainTbl
% ProblemType - (1,1) string, "classification" or "regression"
% CVPartition - (1,1) cvpartition over height(RawTrainTbl) rows with
% NumTestSets >= 2; test(CVPartition,k) gives fold k's held-out
% rows. The caller owns stratification / grouping / K, and
% whether the partition covers the train block (default flow)
% or all rows (whole-data k-fold mode).
% Options.TargetModel - (1,1) string model family, passed to the producer
% and baselineComparison (default "agnostic")
% Options.Producer - (1,1) function_handle, the PLUGGABLE generator (see
% below). Default is the SMLT gencfeatures producer, so
% the SMLT path is unchanged; a domain path injects a
% producer that re-runs its extraction per fold.
%
% THE PLUGGABLE PRODUCER. Generation is injected so this one loop serves both
% the SMLT path and a domain path (Mode 3 in either case). The producer is
% [EngTrain, Apply, ExcludeFeatures] = Producer(FoldTrainRaw, Response, ...
% ProblemType, TargetModel)
% where EngTrain is the engineered TRAINING table (predictors + response), Apply
% is a function handle mapping a raw table to the engineered pool (the fold's
% fitted recipe -- transform(Transformer,.) for SMLT, Recipe.Apply for a domain
% skill) used to engineer the held-out rows leakage-safely, and ExcludeFeatures
% are names to drop before ranking (e.g. GenInfo.BinaryReliant; string.empty for
% a domain pool). The default SMLT producer wraps generateFeatures; because it
% refits per fold, the loop already handles a pool that differs fold to fold, so
% a domain producer needs no special-casing.
%
% Output:
% Result - struct with fields:
% .K, .MetricName, .TargetModel
% .Performance.Engineered / .Original / .Naive / .Improvement
% - each a struct(.Mean, .Std, .PerFold), for the primary
% metric (.MetricName: AUC or RMSE)
% .Performance.Secondary - ordered struct array of companion metrics
% any fold recorded (classification: macro-F1 always,
% accuracy when balanced), each element
% struct(Name, Engineered, Original) with Engineered /
% Original a meanStd struct; empty (1x0) when none
% (e.g. regression)
% .Performance.Panel - ordered struct array, one element per trained
% family (single family when declared; bag/linear/kernel
% under agnostic), each aggregated mean +/- std as above
% .QualityStability - engineered-side model-free quality across
% folds: struct with MaxRelevance,
% NumRelevant, MeanRedundancy, MaxRedundancy,
% EffectiveDim (each a meanStd struct)
% .PerFold - struct array (.Metric, .NumSelected, .PoolSize)
% .Reasoning - human-readable summary
% Copyright 2026 The MathWorks, Inc.
arguments
RawTrainTbl table
Response (1,1) string
ProblemType (1,1) string {mustBeMember(ProblemType, ["classification","regression"])}
CVPartition (1,1) cvpartition
Options.TargetModel (1,1) string {mustBeMember(Options.TargetModel, ...
["agnostic","tree_ensemble","linear","kernel_distance"])} = "agnostic"
Options.Producer (1,1) function_handle = @smltProducer
end
AllVars = string(RawTrainTbl.Properties.VariableNames);
if ~ismember(Response, AllVars)
error('assessKFold:responseNotFound', ...
'Response variable "%s" is not a column of the input table.', Response);
end
OriginalPredVars = setdiff(AllVars, Response, "stable");
% The original-reference baseline fits a learner on these raw columns, so the
% reference can only hold model-ready predictor types. datetime/duration
% columns are valid GENERATION inputs (the producer extracts components from
% them, so they still shape the engineered pool) but a learner cannot fit a
% bare datetime -- exclude those types from the ORIGINAL reference only.
IsModelReady = ~varfun(@(c) isdatetime(c) || isduration(c) || isa(c, "calendarDuration"), ...
RawTrainTbl(:, OriginalPredVars), OutputFormat = "uniform");
OriginalPredVars = OriginalPredVars(IsModelReady);
if CVPartition.NumObservations ~= height(RawTrainTbl)
error('assessKFold:partitionSizeMismatch', ...
'CVPartition was built for %d observations but the table has %d rows.', ...
CVPartition.NumObservations, height(RawTrainTbl));
end
K = CVPartition.NumTestSets;
if K < 2
error('assessKFold:tooFewFolds', ...
'CVPartition must define at least 2 folds; got %d.', K);
end
fprintf(['assessKFold: re-running generate -> select -> score on %d folds. ' ...
'The producer refits per fold, so expect ~%dx a single generation''s cost.\n'], K, K);
% --- Per-fold loop ---------------------------------------------------------
EngMetric = nan(K, 1);
OrigMetric = nan(K, 1);
NaiveMetric = nan(K, 1);
ImprovMetric = nan(K, 1);
% Companion classification metrics, aggregated alongside the primary. Macro-F1
% is always recorded for classification; accuracy only when the fold panel
% logged it (balanced problems). NaN for folds/problem types that lack them.
MacroF1Eng = nan(K, 1);
MacroF1Orig = nan(K, 1);
AccEng = nan(K, 1);
AccOrig = nan(K, 1);
% Engineered-side model-free quality per fold. Each fold scores its own
% regenerated+reselected set on its TRAINING rows, engineered side only;
% aggregated mean +/- std below.
QMaxRel = nan(K, 1);
QNumRel = nan(K, 1);
QMeanRed = nan(K, 1);
QMaxRed = nan(K, 1);
QEffDim = nan(K, 1);
% Full per-family panel each fold (all trained families, not just the primary),
% so agnostic can report bag/linear/kernel side by side. baselineComparison
% always returns .Panel, so this is populated for every fold.
PanelPerFold = cell(K, 1);
PerFold = repmat(struct(Metric = NaN, NumSelected = 0, PoolSize = 0), 1, K);
MetricName = "";
for k = 1:K
TestRows = test(CVPartition, k);
FoldTrain = RawTrainTbl(~TestRows, :);
FoldTest = RawTrainTbl(TestRows, :);
% Generate on fold-train ONLY (leakage-safe) via the pluggable producer;
% Apply reproduces this fold's pool on any raw rows for the held-out score.
[EngTrain, Apply, ExcludeFeatures] = Options.Producer(FoldTrain, Response, ...
ProblemType, Options.TargetModel);
PoolNames = setdiff(string(EngTrain.Properties.VariableNames), Response, "stable");
% Select on the fold's engineered training pool.
SelectedNames = runConsensusSelection(EngTrain, Response, ProblemType, ...
ExcludeFeatures = ExcludeFeatures);
% Build combined engineered + raw tables (train rows first, then test)
% so baselineComparison scores this fold's selected set out-of-fold.
RawCombined = [FoldTrain; FoldTest];
EngCombined = combineEngineered(EngTrain, Apply, RawCombined, Response);
nTrain = height(FoldTrain);
TrainIdxLocal = (1:nTrain)';
ValIdxLocal = (nTrain + 1 : height(RawCombined))';
% Cast integer originals to double in the diagnostic REFERENCE only (the
% fitters and the MI panel accept floating-point, not integer types); the
% producer above already generated on the untouched integer columns, so the
% pool is unaffected. datetime/duration are already dropped from
% OriginalPredVars, so they are never referenced here.
RawCombinedRef = castReferenceIntegers(RawCombined, OriginalPredVars);
FoldResult = baselineComparison(RawCombinedRef, EngCombined, TrainIdxLocal, ValIdxLocal, ...
Response, OriginalPredVars, SelectedNames, ProblemType, ...
TargetModel = Options.TargetModel, InternalCV = false);
EngMetric(k) = FoldResult.Engineered;
OrigMetric(k) = FoldResult.Original;
NaiveMetric(k) = FoldResult.Naive;
ImprovMetric(k) = FoldResult.Improvement;
MetricName = FoldResult.Metric;
% Companion metrics when this fold's panel carries them.
if isfield(FoldResult, 'MacroF1')
MacroF1Eng(k) = FoldResult.MacroF1.Engineered;
MacroF1Orig(k) = FoldResult.MacroF1.Original;
end
if isfield(FoldResult, 'Accuracy')
AccEng(k) = FoldResult.Accuracy.Engineered;
AccOrig(k) = FoldResult.Accuracy.Original;
end
PanelPerFold{k} = FoldResult.Panel;
% Model-free quality of THIS fold's selected set, on its training rows
% (EngTrain is row-aligned with FoldTrain). Engineered side only; the
% original-side numbers are discarded here (the shipped-set read at
% delivery owns the raw-vs-engineered contrast).
FoldTrainRef = castReferenceIntegers(FoldTrain, OriginalPredVars);
FoldQuality = featureSetQuality(FoldTrainRef, EngTrain, (1:height(EngTrain))', ...
Response, OriginalPredVars, SelectedNames, ProblemType, Verbose = false);
QMaxRel(k) = FoldQuality.Relevance.MaxEngineered;
QNumRel(k) = FoldQuality.Relevance.NumRelevantEngineered;
QMeanRed(k) = FoldQuality.Redundancy.MeanPairwiseMIEngineered;
QMaxRed(k) = FoldQuality.Redundancy.MaxPairwiseMIEngineered;
QEffDim(k) = FoldQuality.Compactness.EffectiveDimEngineered;
PerFold(k) = struct(Metric = FoldResult.Engineered, ...
NumSelected = numel(SelectedNames), PoolSize = numel(PoolNames));
fprintf(' Fold %d/%d: pool=%d, selected=%d, %s(eng)=%.3f\n', ...
k, K, numel(PoolNames), numel(SelectedNames), MetricName, FoldResult.Engineered);
end
% --- Aggregate performance -------------------------------------------------
Result = struct();
Result.K = K;
Result.MetricName = MetricName;
Result.TargetModel = Options.TargetModel; % declared family, for report labelling
Result.Performance = struct( ...
Engineered = meanStd(EngMetric), ...
Original = meanStd(OrigMetric), ...
Naive = meanStd(NaiveMetric), ...
Improvement = meanStd(ImprovMetric));
% Companion metrics, aggregated the same way and stored under .Secondary as an
% ordered struct array {Name, Engineered, Original} so a metric only appears
% when at least one fold recorded it. Consumers (summary, reports) loop this
% without hard-coding which companions exist.
Result.Performance.Secondary = aggregateSecondary( ...
{"macro-F1", MacroF1Eng, MacroF1Orig; "accuracy", AccEng, AccOrig});
% Per-family panel: aggregate every trained family across folds the same way as
% the primary above. Under a declared model this is a single family (identical
% to the top-level fields); under agnostic it is bag/linear/kernel, so reports
% and the grouped plot can show all three. The top-level .Engineered/.Original/
% etc. remain the PRIMARY family so existing consumers are unaffected.
Result.Performance.Panel = aggregatePanel(PanelPerFold, K);
Result.PerFold = PerFold;
% --- Representation-quality stability across folds -------------------------
Result.QualityStability = struct( ...
MaxRelevance = meanStd(QMaxRel), ...
NumRelevant = meanStd(QNumRel), ...
MeanRedundancy = meanStd(QMeanRed), ...
MaxRedundancy = meanStd(QMaxRed), ...
EffectiveDim = meanStd(QEffDim));
Result.Reasoning = buildReasoning(Result, MetricName);
fprintf('%s\n', Result.Reasoning);
end
function Tbl = castReferenceIntegers(Tbl, PredVars)
%castReferenceIntegers Cast integer predictor columns to double, reference-only.
% The original-reference diagnostics (baselineComparison fitters, the MI panel's
% floating-point check) accept double but not integer types. Integers are valid
% predictors once cast, so widen them here in the reference copy only; generation
% already ran on the untouched columns. Non-integer columns are left as-is.
for i = 1:numel(PredVars)
Col = Tbl.(PredVars(i));
if isinteger(Col)
Tbl.(PredVars(i)) = double(Col);
end
end
end
function EngCombined = combineEngineered(EngTrain, Apply, RawCombined, Response)
%combineEngineered Engineer the combined (train+test) raw rows in ONE Apply.
% Applying the fold's recipe separately to train and test can yield engineered
% categorical (binned) columns with different category sets, so a later vertcat
% fails. Applying it to the combined raw table once gives every engineered
% column a single consistent category set. It stays leakage-safe: the recipe
% was fit on the fold's TRAINING rows only, so the test rows only ever have that
% fitted recipe applied, never re-fit. Apply is the producer's fold recipe
% (SMLT transform(Transformer,.) or a domain Recipe.Apply). The response is
% reattached from the raw table and columns are aligned to EngTrain's order.
EngCombined = Apply(RawCombined);
if ~ismember(Response, string(EngCombined.Properties.VariableNames))
EngCombined.(Response) = RawCombined.(Response);
end
EngCombined = EngCombined(:, EngTrain.Properties.VariableNames);
end
function [EngTrain, Apply, ExcludeFeatures] = smltProducer(FoldTrainRaw, Response, ProblemType, TargetModel)
%smltProducer Default producer: gencfeatures/genrfeatures via generateFeatures.
% Fits the SMLT FeatureTransformer on the fold's training rows and returns its
% transform method as the Apply handle, so held-out rows are engineered with the
% fold-fitted recipe (never re-fit). ExcludeFeatures forwards the binary-reliant
% WoE columns generateFeatures flags, matching the delivered selection run.
[EngTrain, Transformer, GenInfo] = generateFeatures(FoldTrainRaw, Response, ...
ProblemType, TargetModel = TargetModel);
Apply = @(RawTbl) transform(Transformer, RawTbl);
ExcludeFeatures = GenInfo.BinaryReliant;
end
function MS = meanStd(V)
%meanStd Mean/std over folds ignoring NaN, plus the raw per-fold vector.
MS = struct(Mean = mean(V, "omitnan"), Std = std(V, "omitnan"), PerFold = V(:)');
end
function Secondary = aggregateSecondary(Spec)
%aggregateSecondary Aggregate each companion metric that any fold recorded.
% Spec is an N-by-3 cell array {Name, EngVec, OrigVec}. A metric is included
% only when at least one fold produced a finite value (so regression, which has
% no companion, and balanced-only accuracy, drop out cleanly). Returns an
% ordered struct array with fields Name/Engineered/Original, each aggregate a
% meanStd struct -- empty (1x0) when nothing qualified.
Secondary = struct('Name', {}, 'Engineered', {}, 'Original', {});
for i = 1:size(Spec, 1)
EngVec = Spec{i, 2};
if ~any(isfinite(EngVec))
continue
end
Secondary(end+1) = struct( ...
Name = string(Spec{i, 1}), ...
Engineered = meanStd(EngVec), ...
Original = meanStd(Spec{i, 3})); %#ok<AGROW>
end
end
function Families = aggregatePanel(PanelPerFold, K)
%aggregatePanel Aggregate each trained family's metrics across folds.
% PanelPerFold{k} is fold k's baselineComparison .Panel (a struct array, one
% entry per trained family). Families are identified by .Family and aggregated
% independently, mean +/- std across folds, mirroring the primary aggregation.
% Returns an ordered struct array with one element per family, fields:
% .Family, .Engineered/.Original/.Naive/.Improvement (each a meanStd struct),
% .Secondary (companion metrics, same shape as the top-level .Secondary).
% Family order follows the first fold's panel (bag, linear, kernel for agnostic).
Families = struct('Family', {}, 'Engineered', {}, 'Original', {}, ...
'Naive', {}, 'Improvement', {}, 'Secondary', {});
if K < 1 || isempty(PanelPerFold{1})
return
end
FamilyNames = string({PanelPerFold{1}.Family});
for f = 1:numel(FamilyNames)
Name = FamilyNames(f);
EngV = nan(K, 1); OrigV = nan(K, 1); NaiveV = nan(K, 1); ImprovV = nan(K, 1);
MacroEngV = nan(K, 1); MacroOrigV = nan(K, 1);
AccEngV = nan(K, 1); AccOrigV = nan(K, 1);
for k = 1:K
FR = familyEntry(PanelPerFold{k}, Name);
if isempty(FR)
continue
end
EngV(k) = FR.Engineered;
OrigV(k) = FR.Original;
NaiveV(k) = FR.Naive;
ImprovV(k) = FR.Improvement;
if isfield(FR, 'MacroF1')
MacroEngV(k) = FR.MacroF1.Engineered;
MacroOrigV(k) = FR.MacroF1.Original;
end
if isfield(FR, 'Accuracy')
AccEngV(k) = FR.Accuracy.Engineered;
AccOrigV(k) = FR.Accuracy.Original;
end
end
Families(f) = struct( ...
Family = Name, ...
Engineered = meanStd(EngV), ...
Original = meanStd(OrigV), ...
Naive = meanStd(NaiveV), ...
Improvement = meanStd(ImprovV), ...
Secondary = aggregateSecondary( ...
{"macro-F1", MacroEngV, MacroOrigV; "accuracy", AccEngV, AccOrigV}));
end
end
function FR = familyEntry(Panel, Name)
%familyEntry The panel entry for a named family, or [] if absent this fold.
FR = [];
for i = 1:numel(Panel)
if string(Panel(i).Family) == Name
FR = Panel(i);
return
end
end
end
function Reasoning = buildReasoning(Result, MetricName)
%buildReasoning One-line audit summary of the held-out performance read.
Eng = Result.Performance.Engineered;
Reasoning = string(sprintf( ...
"K=%d: %s(eng)=%.3f+/-%.3f, improvement=%.3f+/-%.3f.", ...
Result.K, MetricName, Eng.Mean, Eng.Std, ...
Result.Performance.Improvement.Mean, Result.Performance.Improvement.Std));
end
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/ai-and-statistics/matlab-engineer-tabular-features · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks.
Get it from the source
8 of this skill’s files are not mirrored here, so there is no ZIP. Get the complete skill from its source: matlab/matlab-agentic-toolkit