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://mp-staging.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/wf-align-channels.md

Workflow: align multi-rate / offset channels to a shared time base

Functions used: synchronize, retime, resample, finddelay, alignsignals, xcorr

Several signals from different sources — different sample rates, different start times, or an unknown lag between them — become one aligned, uniformly sampled table.

Off-ramp. If a single channel just has non-uniform / jittery timestamps (no second channel to align against), that is regularize, not align — see wf-uniform-rate.md.

When to use this

Reach here when the inputs are two or more channels that need a common time base:

  • Different rates (100 Hz accelerometer + 50 Hz pressure).

  • Different start times or offsets.

  • An unknown lag to estimate and remove first.

The dominant mistake is hand-orchestrating the merge: retime channel B, estimate the lag, shift B's row times, retime again, then build a timetable by hand to concatenate. That produces the correct result but in five steps. synchronize does the bring-to-common-grid step in one call.

Recipe

Step 1 — Get each channel into a timetable

If the channels are numeric vectors with sample rates, wrap them:

A = timetable(secondsA', chA, 'VariableNames', "accel");   % or SampleRate= form
B = timetable(secondsB', chB, 'VariableNames', "press");

Once they are timetables, the merge is one function — the rate difference is handled by the adjust method, not by manual resampling per channel.

Step 2 (only if there is an unknown lag) — estimate and remove it

If the channels are the same physical signal seen through different sensors with an unknown delay, find the lag first. Both finddelay and a normalized xcorr peak give it; they should agree.

d = finddelay(a, b);              % integer-sample lag of b relative to a
b_aligned = alignsignals(a, b);   % or shift b's row times by d/fs

When you report the lag to the user, lead with the physical time in seconds — that is unambiguous across channels. finddelay/xcorr measure the lag in samples of the grid the two signals were compared on, so a raw sample count only means something once you say which rate it is at. Report the delay as seconds (d/fsCommon, where fsCommon is the shared/aligned rate), and if you also give a sample count, state the grid it refers to (e.g. "8 ms = 8 samples at the 1 kHz aligned rate"). Do not report a bare integer sample count for mismatched-rate channels — the same delay is a different count at each rate.

For sub-sample precision, refine the xcorr peak parabolically. Skip this whole step when the channels are different signals sharing a clock — there is no lag to estimate, only a rate/offset difference, which step 3 handles directly.

Step 3 — Merge onto a shared grid with synchronize

This is the one-shot primitive. Pick the common time basis and the adjust method (full contract in fn-synchronize.md):

% Put everything on A's row times, interpolate B linearly:
TT = synchronize(A, B, 'first', 'linear');

% Or a clean uniform output rate, regardless of either input's grid:
TT = synchronize(A, B, 'regular', 'linear', 'SampleRate', 100);

% Or keep only the overlapping span (drop non-overlapping tails):
TT = synchronize(A, B, 'commonrange', 'linear');

Choose the basis by intent:

  • 'first' / 'last' — anchor to one channel's existing grid.

  • 'regular' + SampleRate — impose a clean uniform rate.

  • 'commonrange' — keep only where all channels have data.

  • 'union' (default) — keep every sample and NaN-fill the rest (see step 4).

Anti-pattern. Do not retime each channel separately and then build a timetable by hand to stitch them. synchronize is exactly that operation, done once, with the grid choice explicit.

% Bad — hand-orchestrated merge:
Br = retime(B, A.Time, 'linear');
TT = timetable(A.Time, A.accel, Br.press);   % manual concat

% Good — one call:
TT = synchronize(A, B, 'first', 'linear');
Step 4 — Handle the NaNs that alignment creates

At times where one channel has no sample and you used the default ('fillwithmissing', i.e. synchronize(A,B) with no method), or where 'union' introduced rows outside a channel's span, the output has NaNs. Align typically precedes fill: decide whether those gaps are interpolated, held, or left missing. See wf-repair-missing.md for the fill step.

If you interpolated in step 3 ('linear' etc.), watch the endpoints: 'linear' extrapolates by default, so a channel that starts late gets invented values before its first real sample. Pass EndValues=NaN to refuse extrapolation, then fill deliberately.

Two mistakes are common at exactly this step, both on the NaNs alignment just created:

  • Dropping the NaN rows (tt = tt(all(isfinite(tt{:,:}),2), :)) to make the table finite. That silently truncates every channel to the overlap span and desynchronizes rows you meant to keep - it is not a fill, it is a crop. If you genuinely want only the overlap, ask synchronize for it up front with 'commonrange'; do not post-hoc delete rows.

  • Treating the endpoint NaNs as ordinary interior gaps. A late-starting channel's leading NaNs (and an early-ending channel's trailing NaNs) are edge gaps with data on one side only - the endpoint case in wf-repair-missing.md. Route them there; on an oscillatory channel the fill is fillgaps, not fillmissing(..., EndValues=...).

Aliasing guardrail — resample before synchronize when downsampling

synchronize/retime interpolation methods do not antialias, and they alias silently. If a channel is being brought onto a grid coarser than its own content bandwidth (any real downsampling), plain interpolation folds high-frequency energy back into the band with no warning.

Rule: when the shared grid is coarser than a channel's native rate, resample that channel to the target rate first (antialiased, resample applies the FIR anti-alias filter), then synchronize onto the grid. Reserve bare synchronize-linear for channels whose content is slow relative to the shared rate — i.e. you are not reducing real bandwidth. See fn-resample.md and wf-uniform-rate.md (the single-channel rate-change workflow).

See also

  • fn-synchronize.md — the merge primitive, basis and method contract.

  • fn-retime.md — single-channel rate change (the piece synchronize generalizes).

  • fn-resample.md — antialiased rate conversion.

  • wf-repair-missing.md — fill the NaNs alignment creates.

  • wf-uniform-rate.md — single-channel onto a uniform rate (regularize jitter or plain rate-change).


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.

Download ZIP

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