Generated banner for Matlab Prepare Signal Data
Generated logo for Matlab Prepare Signal Data

Matlab Prepare Signal Data

MathWorksOfficialCreated by MathWorks

  • Skill
  • Tool integration
  • Data and AI
  • BSD-2-Clause
  • No issues found

From the author

Use this skill when conditioning, loading, preparing, or labeling signal data for analysis or ML training. Covers: cleaning a single signal (fill gaps, remove drift, deoutlier, denoise, resample/align a time base) BEFORE analysis; building a `signalDatastore` pipeline; creating a `labeledSignalSet` for Signal Labeler; deriving labels (filename, folder, in-file, ROI, time-frequency ROI); stratified train/val/test splits; framing long signals; parallel processing; and shaping datastore output for `trainnet`. Triggers include "clean up this signal", "remove drift / detrend", "fill gaps", "remove spikes / outliers", "denoise", "resample to a uniform rate", "align channels", "labels from filenames", "stratified split", "prepare for Signal Labeler", and function names like `fillgaps`, `fillmissing`, `detrend`, `filloutliers`, `smoothdata`, `resample`, `synchronize`, `signalDatastore`, `labeledSignalSet`, `filenames2labels`, `folders2labels`, `splitlabels`, `framesig`, `framelbl`, `createDatastores`.
— the description by MathWorks

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to signal data preparation, guiding users through the lifecycle of cleaning raw signals, managing datastores, applying labels, and partitioning data for machine learning. It emphasizes using high-level Signal Processing Toolbox functions to ensure readability and maintainability, while offering clear heuristics for ordering conditioning steps like detrending, smoothing, and outlier removal. The skill is designed to help users move from raw data to a ready-to-train state for models like trainnet.

What it does

  • Cleans signals by filling gaps, removing drift, denoising, and handling outliers.
  • Synchronizes and resamples multi-channel data onto a uniform time base.
  • Builds data pipelines using signalDatastore for efficient loading.
  • Creates labeledSignalSet objects for structured labeling and Signal Labeler interoperability.
  • Performs stratified splits and framing for long signal sequences.
  • Shapes and prepares datastore outputs for machine learning workflows.

When to use it

  • When you need to clean a single signal before analysis or training.
  • When preparing a dataset of signals for machine learning with specific labeling requirements.
  • When you need to align multiple signal channels or resample them to a uniform rate.
  • When you need to partition signal data into training, validation, and test sets.
  • When you need to frame long signals for windowed analysis or supervision.

Advantages

  • Promotes readable, maintainable code by preferring high-level toolbox functions.
  • Provides a logical, verified order for conditioning steps to prevent data corruption.
  • Reduces manual effort by automating common tasks like label derivation from filenames.
  • Ensures compatibility with Signal Labeler and deep learning training functions.
  • Offers clear guidance on when to escalate to lower-level methods.

Usage examples

“How do I remove a linear trend from my signal?”
The agent will recommend using detrend(x, 1) and explain why explicit degree specification is preferred for code clarity.
“I have a folder of signal files; how do I create a datastore and split them for training?”
The agent will guide you through using signalDatastore to load the files, followed by splitlabels to perform a stratified split.
“My signal has gaps; how should I fix them?”
The agent will suggest using fillmissing for short gaps or fillgaps for longer gaps in oscillatory signals, depending on the signal characteristics.
“How do I align two signals with different sampling rates?”
The agent will recommend using the synchronize function to place both signals onto a shared time grid.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/matlab/matlab-prepare-signal-data/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip matlab-prepare-signal-data.zip -d .agents/skills

Documentation by MathWorks

Prepare Signal Data

Look in Signal Processing Toolbox first. The conditioning, labeling, splitting, framing, and partitioning helpers here live in Signal Processing Toolbox — not in Stats & ML Toolbox or generic-MATLAB string utilities.

The arc: condition a raw signal (clean it) -> load a folder into a datastore -> label -> split / frame -> hand off to trainnet. Each stage is a workflow file; this page routes you to the right one.

When to Use

  • Cleaning a single signal before analysis: fill gaps, remove drift, deoutlier, denoise, put it on a uniform time base, align multiple channels.

  • Loading / preparing signal data for ML training: datastores, labels from filenames or folders, stratified splits, framing, parallel processing.

  • Structured labeling: labeledSignalSet for Signal Labeler, all label types.

When NOT to Use

  • Raw .wav audio classification with Audio Toolbox available. audioDatastore is the canonical path (this skill's custom-ReadFcn workflow handles .wav only when Audio Toolbox is absent — references/wf-custom-readfcn.md).

  • Frequency-selective filter DESIGN (band isolation, notch, custom FIR/IIR) — see the matlab-design-digital-filter skill. This skill's conditioning is about cleaning, not designing filters.

  • Computing per-frame features (RMS, crest factor, spectral / bandwidth, time-frequency features) from an already-conditioned signal — see the matlab-extract-signal-features skill. This skill's framesig / framelbl are for manual per-window labeling / supervision, not for deriving a feature table; the signal*FeatureExtractor objects window internally and emit the table.

Best practices

  • Deliverable is a runnable .m script the user can save, version, and re-run — not workspace state.

  • Prefer the highest-level function that does the job. detrend / smoothdata / fillmissing / resample read cleanly and are easy for a non-expert to follow. Drop to a lower-level / more-configurable path (designfilt + filtfilt, a hand-built AR model, a named primitive) only when you need control the high-level call cannot give, or when the user asks. Readability first; escalate to low-level for necessity, not by default.

    • The high-level call usually exposes the control you think you need. In particular smoothdata(x, "sgolay", fl) takes the frame length fl as an argument — it does NOT hide it — so prefer it over calling sgolayfilt directly. Reach for sgolayfilt only for what the dispatcher genuinely lacks (derivative output via dn, or an unusual polynomial order).

0. Common reflexes

If your first instinct is one of these, the canonical replacement is one row away.

ReflexCanonicalDetail
Hand-design a highpass/designfilt to remove a smooth driftdetrend(x, n) — escalate n = 1 -> 2 -> 3 before reaching for a filter; polynomial detrend has unity passband gainreferences/fn-detrend.md
Invent a gap-filler (regularizeNaNs, inpaintn — not real)fillmissing (interp) for short gaps; fillgaps (SPT, AR) for long gaps in oscillatory signalsreferences/wf-repair-missing.md
Hand-roll retime + shift + retime + concat to align channelssynchronize(A, B, ...) — one call to a shared gridreferences/wf-align-channels.md
Custom ReadFcn for a .csvsignalDatastore default reader + SignalVariableNamesreferences/fn-signaldatastore.md
cvpartition for a datastore splitsplitlabels + subset(ds, idx{k})references/fn-splitlabels.md
regexp / extractBefore / fileparts for labels from filenamesfilenames2labels(sds, Extract=...)references/fn-filenames2labels.md
regexp / nested fileparts for labels from subfoldersfolders2labels(sds.Files)references/fn-folders2labels.md
Manual framing loop with (i-1)*hop+1framesig(x, fl, OverlapLength=...)references/wf-frame-and-label.md
Manual ROI-to-frame vote with containers.Mapframelbl(rois, ...)references/wf-frame-and-label.md
for loop load(file) to read in-file label variablessignalDatastore(folder, SignalVariableNames=["x","label"])references/fn-signaldatastore.md
signalMask when you need Signal Labeler interoplabeledSignalSet with ROI labels (signalMask can't import)references/fn-labeledsignalset.md
signalLabeler(lss) (pass the set as an arg)Launch bare signalLabeler (zero args), then Import -> From Workspace or From Filereferences/wf-label-and-export.md

SPT-specialized functions exist — reach for them, don't reinvent. fillgaps (AR gap fill), medfilt1 / hampel (impulse handling), sgolayfilt / smoothdata(...,"sgolay") (feature-preserving smoothing) are in Signal Processing Toolbox.

1. Workflows

Each workflow file is the entry point and lists the functions it uses. Start here.

WorkflowUse whenReference
Repair missing samplesNaN gaps / dropouts to fill.references/wf-repair-missing.md
Detrend, smooth, deoutlierDrift, spikes, and/or broadband noise on one signal (smoothing/denoising lives here).references/wf-detrend-smooth-deoutlier.md
Align multi-rate / offset channelsSeveral channels onto a shared time base.references/wf-align-channels.md
Put one channel on a uniform rateOne channel -> uniform grid at a chosen rate: jittery timestamps to regularize, OR already uniform but the wrong rate to resample.references/wf-uniform-rate.md
Wavelet denoising (escalation)Non-stationary/multi-scale noise a tuned sgolayfilt can't remove; wdenoise (Wavelet TB).references/wf-denoise.md
Envelope extractionAmplitude outline (AM demod, peak hull) — not cleaning.references/wf-envelope.md
Load + label + splitFolder of files -> datastore for training.references/wf-load-and-split.md
Frame long signals + per-frame labelsLong signals, per-window supervision.references/wf-frame-and-label.md
Label + export (all label types)Structured labels (attribute/ROI/point/TF-ROI), export to Signal Labeler / DL.references/wf-label-and-export.md
Parallel processing across a parpoolPer-signal work across workers.references/wf-parallel-process.md
Custom ReadFcn (only when needed)Format isn't .mat / .csv, or has a metadata prelude.references/wf-custom-readfcn.md
Hand-off to trainnetDatastore ready; shape for trainnet / combine.references/wf-handoff-to-dl.md

Each workflow file names the fn- reference pages for the functions it uses; there is no separate function index — enter through the workflow that matches your task, or the reflex table above.

2. Ordering when a signal needs several conditioning steps

The governing principle (this is the real rule): order the steps so an earlier operation does not corrupt the input to a later one. Spikes bias least-squares fits and get smeared by filters/resamplers; an un-removed trend gets averaged into the signal by a smoother; most operations choke on NaN. Reason from that for the signal in front of you — do not follow a fixed chain blindly.

Default heuristic (a good starting order, not a universal law):

outliers -> detrend -> smooth, with fill and align placed by the principle above.

  • outliers -> detrend -> smooth is the verified core: remove spikes before a polynomial detrend (a spike biases the fit) and before a smoother (a smoother spreads the spike across its window); detrend before smooth so the smoother isn't averaging across a trend.

  • Fill NaN before any step that can't handle missing data (detrend, filters, most smoothers).

  • Align / resample: putting a signal on a new grid (retime/synchronize) creates NaN at non-overlapping times, so fill after aligning. BUT if the signal has spikes, deoutlier before resampling — resample's anti-alias filter will smear an un-removed spike. So align-vs-outliers order depends on the signal; the principle decides, not a fixed sequence.

Not every signal needs every step — identify which apply, order them by the principle, and each workflow file has an off-ramp if your problem is actually a different family.


Copyright 2026 The MathWorks, Inc.


Files

references/fn-labeledsignalset.md

Function: labeledSignalSet

Used in: wf-label-and-export.md Toolbox: Signal Processing Toolbox Since: R2018b (roiTimeFrequency support since R2025a)

Store labeled signals alongside label definitions. The container that ties signals, label definitions, and label values together.

Signatures

lss = labeledSignalSet                                  % empty
lss = labeledSignalSet(src)                             % from data source
lss = labeledSignalSet(src, lbldefs)                    % with label definitions
lss = labeledSignalSet(src, lbldefs, Name=Value)        % with properties

Data sources (src)

Source formMembersSignals per member
Numeric matrix NxM1M columns
Cell array of matrices {NxM, PxQ, ...}numel(cell)columns per matrix
Cell array of cell vectors {{v1}, {v2, v3}}numel(outer)numel(inner), variable length
Timetable1variables
Cell array of timetablesnumel(cell)variables per TT
signalDatastorenumber of filessignals per file
audioDatastorenumber of fileschannels per file

Properties

PropertySettableNotes
Sourceat creation onlyData source
NumMembersread-onlyNumber of members
Labelsread-onlyTable; rows = members, columns = label definitions
TimeInformationread-only"none" | "sampleRate" | "sampleTime" | "timeValues" | "inherent"
DescriptionyesFree text
SampleRateat creation onlyScalar or vector (one per member)
SampleTimeat creation onlyScalar/vector/duration
TimeValuesat creation onlyVector/matrix/cell

Key object functions

Adding/removing structure
FunctionDoes
addMembers(lss, newSrc)Append members
removeMembers(lss, idx)Remove by index
addLabelDefinitions(lss, defs)Add label definitions after creation
removeLabelDefinition(lss, name)Remove a label definition
editLabelDefinition(lss, name, NV)Edit definition properties
Setting/getting label values
FunctionSignature
setLabelValueSee per-type signatures below
getLabelValues(lss)Full label table
getLabelValues(lss, idx, name)One label for one member
getLabelValues(lss, idx, [parent child])Sublabel values
resetLabelValues(lss, idx, name)Reset to defaults
removeRegionValue(lss, idx, name, rowIdx)Remove specific ROI row
removePointValue(lss, idx, name, rowIdx)Remove specific point row
Querying
FunctionReturns
getLabelNames(lss)String array of label names
getLabelDefinitions(lss)signalLabelDefinition vector
getLabelIndices(lss, name)Index information
getMemberNames(lss)Member name strings
setMemberNames(lss, names)Rename members
getSignal(lss, idx)Raw signal data
getLabeledSignal(lss, idx)Signal + labels together
countLabelValues(lss, name)Per-class counts and percentages
labelDefinitionsHierarchy(lss)Text hierarchy
labelDefinitionsSummary(lss)Summary table
head(lss)Top rows of Labels table
Export
FunctionReturns
createDatastores(lss, labelNames)[signalDS, labelDS] for ML training
createDatastores(lss, name, TF NV-pairs)TF image + mask datastores (R2025a)
createFeatureData(lss, ...)Feature table/matrix + response vectors
merge(lss1, lss2)Combined labeled signal set
subset(lss, idx)New lss with subset of members

setLabelValue — per-type signatures

Attribute
setLabelValue(lss, memberIdx, "LabelName", value)
% value: scalar matching LabelDataType
ROI (time-domain)
setLabelValue(lss, memberIdx, "LabelName", roiLimits, values)
% roiLimits: Nx2 [start end] in seconds (or samples if no SampleRate)
% values: Nx1 matching LabelDataType
Point
setLabelValue(lss, memberIdx, "LabelName", locations, values)
% locations: Nx1 time points
% values: Nx1 matching LabelDataType
Time-frequency ROI (R2025a)
setLabelValue(lss, memberIdx, "LabelName", timeLimits, freqLimits, values)
% timeLimits: Nx2 [tStart tEnd] in seconds
% freqLimits: Nx2 [fLow fHigh] in Hz
% values: 1xN or Nx1 matching LabelDataType
Sublabel
setLabelValue(lss, memberIdx, ["Parent" "Child"], ..., LabelRowIndex=k)
% LabelRowIndex selects which parent ROI/point the sublabel belongs to

createDatastores — two modes

Standard (time-domain labels)
[sds, lds] = createDatastores(lss, ["Label1" "Label2" ...])
% sds: signalDatastore — read(sds) returns signal
% lds: arrayDatastore — read(lds) returns table of label values
Time-frequency (R2025a)
[sds, ads] = createDatastores(lss, "TFLabel", ...
    TimeFrequencyMapFormat="image", ...         % "image" | "matrix"
    TimeFrequencyImageSize=[H W], ...           % pixel dimensions
    TimeFrequencyLabelFormat="mask", ...         % "mask" | "table"
    TimeFrequencyMaskPriority=true);            % logical labels only
% sds: reads TF images (HxWx3 uint8 or HxW double)
% ads: reads label masks (HxW logical or HxW categorical)

Canonical pattern — full pipeline

% 1. Define labels
lblClass = signalLabelDefinition("Type", ...
    LabelType="attribute", LabelDataType="categorical", ...
    Categories=["normal" "fault"]);
lblROI = signalLabelDefinition("Event", ...
    LabelType="roi", LabelDataType="logical");

% 2. Create labeled signal set
lss = labeledSignalSet(signals, [lblClass lblROI], ...
    SampleRate=Fs, MemberNames=memberNames);

% 3. Set values
setLabelValue(lss, 1, "Type", "normal");
setLabelValue(lss, 1, "Event", [0.5 1.2; 2.0 2.8], true(2,1));

% 4. Verify
countLabelValues(lss, "Type")

% 5. Export
[sds, lds] = createDatastores(lss, ["Type" "Event"]);

Signal Labeler round-trip

signalLabeler takes NO input arguments. Do NOT write signalLabeler(lss) - it errors (Too many input arguments; the app accepts zero args since R2019a). Launch it bare, then import via the app menu.

% Export to workspace, open Signal Labeler
save("myLabels.mat", "lss");
signalLabeler
% In app: Import -> From Workspace -> select lss

% After labeling in app: Export -> To Workspace -> variable name "lss"
% Continue programmatically with the updated lss

Gotchas

  • SampleRate is read-only after creation. Set it at construction time. If you need different rates per member, pass a vector.

  • Do NOT pass SampleRate when the source is a signalDatastore (or audioDatastore). A datastore already carries inherent time information, so labeledSignalSet(sds, defs, SampleRate=fs) errors with "'SampleRate' is not supported when data source has inherent time information." Drop the argument (the rate comes from the datastore). SampleRate is only for in-memory sources (numeric matrix / cell of matrices) that have no time info of their own.

  • setLabelValue is additive for ROI/point labels. Calling it again appends new regions; it doesn't replace. Use resetLabelValues to clear first, or removeRegionValue to delete specific rows.

  • createDatastores for TF labels requires the label name as a scalar string, not an array. Only one TF label at a time.

  • TimeFrequencyMaskPriority=true only works with logical labels. For categorical TF labels, omit this option.

  • Member names must be unique. Duplicate names error at construction.

  • Labels table row names are the member names. Access via lss.Labels("MemberName", :).

  • Merging two sets requires compatible label definitions. Same names, same types, same categories.

Do-not-guess-this-API gotchas
  • createDatastores has NO per-member overload. The only signatures are createDatastores(lss, lblNames) and createDatastores(lss, lblNames, Name=Value). There is no createDatastores(lss, idx, name) form. For a paired-signal training setup, build the two datastores then combine(sigData, lblData).

  • Cell-of-paths is NOT a valid src. The constructor takes a numeric matrix, a cell array of matrices/cell-vectors, a timetable, a cell array of timetables, a signalDatastore, or an audioDatastore (see the Data-sources table above). A bare cell array of file-path strings is not accepted -- wrap the files in a signalDatastore first, then pass that.

  • signalLabelDefinition('LabelType','roi') rejects xywh-style limits. Time-frequency bounding boxes need 2-column limits per dimension (timeLimits Nx2 + freqLimits Nx2 via LabelType="roiTimeFrequency"), not a single 4-column xywh row. Storing a TF box as a time-domain ROI loses the frequency axis. Use roiTimeFrequency (R2025a) -- see the TF signature above.

See also

  • fn-signallabeldefinition.md — create label definitions.

  • fn-labelspectrogramoptions.md — TF spectrogram options.

  • fn-signalmask-getmask.md — per-sample masks from ROI tables.

  • wf-label-and-export.md — end-to-end labeling workflow.


Copyright 2026 The MathWorks, Inc.


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.

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/signal-processing/matlab-prepare-signal-data · 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 or MathWorks.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-prepare-signal-data.zip