Generated banner for Matlab Analyze Data
Generated logo for Matlab Analyze Data

Matlab Analyze Data

MathWorksOfficialCreated by MathWorks

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

From the author

Analyze data using MATLAB. Use when the task involves tables, timetables, time-series data, numeric arrays, sensor matrices, or gridded data — including but not limited to exploring, row filtering, sorting, cleaning, transforming, aggregating, smoothing, padding, trimming, and answering questions about data. MATLAB provides extensive, easy-to-use built-in functions for these workflows with no additional products required.
— 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 data analysis in MATLAB, focusing on modern, idiomatic practices for handling tables, timetables, and numeric arrays. It emphasizes the use of built-in functions for cleaning, transforming, aggregating, and exploring data, while providing guidance on avoiding legacy patterns and common pitfalls. The skill is designed to help users efficiently answer questions about their data by leveraging MATLAB's native capabilities for data manipulation and statistical analysis.

What it does

  • Generates idiomatic MATLAB code for tabular and time-series data analysis.
  • Provides guidance on cleaning data, including handling missing values and outliers.
  • Supports complex data transformations like filtering, sorting, and reshaping.
  • Facilitates grouped statistics and aggregation using modern functions.
  • Offers techniques for smoothing, trend detection, and pattern analysis.
  • Includes best practices for working with numeric arrays and gridded data.

When to use it

  • When you need to explore, clean, or transform tabular or time-series data.
  • When performing statistical aggregations or group-based analysis.
  • When analyzing sensor matrices or gridded numeric data.
  • When you need to detect patterns, trends, or outliers in your datasets.
  • When you need to answer specific questions about data structure or content.

Advantages

  • Promotes the use of modern, performance-optimized MATLAB functions.
  • Reduces bugs by providing clear guidance on handling missing data and types.
  • Ensures consistent and readable code through idiomatic patterns.
  • Provides direct access to documentation for key data analysis functions.
  • Helps avoid common pitfalls associated with legacy MATLAB syntax.

Usage examples

“How do I calculate the mean sales per region from my table T?”
The agent will provide code using groupsummary(T, 'Region', 'mean', 'Sales') to efficiently compute the requested statistics.
“Clean the missing values in my timetable by forward-filling.”
The agent will generate code using fillmissing(TT, 'previous') to handle gaps in the time-series data.
“Find the top 5 rows in my table based on the 'Revenue' column.”
The agent will suggest using topkrows(T, 5, 'Revenue') for a clean and efficient retrieval.
“How do I smooth a noisy signal in a numeric array?”
The agent will recommend using smoothdata(X, 'movmean', windowSize) to apply a moving average filter.

Install

  1. Download the skill as a ZIP:

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

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

Documentation by MathWorks

MATLAB Data Analysis

Generate idiomatic MATLAB code for tabular data analysis tasks using tables and timetables.

When to Use

  • Any task involving tabular data: exploring, cleaning, transforming, or aggregating tables

  • Time-series analysis: resampling, synchronizing, trend detection, smoothing

  • Answering questions about data in tables (top-N, filtering, group comparisons)

  • Data cleaning: missing values, outliers, type conversion, normalization

When NOT to Use

  • The task has no data context (no tables, timetables, arrays, or date/time values to work with)

  • The primary goal is visualization or plotting, not data analysis (use matlab-build-chart instead)

  • The task is purely symbolic math, simulation, or app building

  • Reading or writing files — CSV, Excel, Parquet, MAT-file (use matlab-import-export-data instead)

  • Data doesn't fit in memory or requires out-of-core processing (use matlab-choose-big-data-solution instead)

  • Storing or retrieving passwords, tokens, or API keys (use matlab-secure-credentials instead)

  • Data lives in a relational database (use matlab-use-database or matlab-use-duckdb instead)

  • Building an ML training pipeline from labeled signal files (use matlab-prepare-signal-data instead)

  • Training classifiers or comparing ML model accuracy on tabular data (use matlab-classify-tabular-data instead)

  • Engineering or selecting features to optimize a supervised ML model (use matlab-engineer-tabular-features instead)

  • Code migration or replacing deprecated APIs (use matlab-modernize-code instead)

Routing: Read references on all relevant topics

This skill covers core MATLAB functions for tabular, time-series, and array-based data workflows — including numeric arrays, sensor matrices, and gridded data. These functions work natively with table, timetable, and numeric arrays, handle missing data correctly, and are performance-optimized. Prefer the modern functions recommended here (e.g., groupsummary, datetime, fillmissing, smoothdata2) over legacy alternatives (e.g., accumarray, nanmean, datenum). Override only if the user explicitly requests otherwise.

Each section below links to a reference file. ALWAYS read the reference file for every relevant topic before writing code. Reference files contain correct syntax, common pitfalls, and "Avoid" patterns that prevent silent bugs. Skipping the reference risks using a deprecated approach or hitting a known pitfall. After reading, state Reference files read: [list] at the top of your response.

Key Functions — Available From

Most functions in this skill are available in R2023a or earlier. The following require a newer release:

FunctionAvailable FromPurpose
paddata, trimdata, resizeR2023bPad, trim, or resize arrays to target length
smoothdata2R2023bSmooth 2-D gridded data over rectangular windows
kdeR2023bKernel density estimate for univariate data
clipR2024aClamp values to a range
islocalmax2, islocalmin2R2024aDetect local extrema in 2-D gridded data
summary (enhanced)R2024bSupports arrays (numeric, datetime, duration, logical); adds Statistics, DataVariables, Detail name-value args
isapproxR2024bTolerance-aware floating-point comparison (use instead of == for computed values)
isbetween (numeric)R2024bCheck elements within a numeric range
numuniqueR2025aCount distinct values in a variable
allbetweenR2025aValidate all values are within a range
alluniqueR2025aValidate all values are unique

Getting Oriented with Data

When data is already in a workspace variable, start by understanding its structure and contents before writing analysis code.

Topics:

  • Summarizing structure, shape, and variable types

  • Assessing how much data is missing and where

  • Understanding distributions (numeric quartiles, categorical value counts)

  • Finding correlations and relationships between variables

  • Checking for duplicates, unique keys, and cardinality

  • Exploring time range, regularity, and temporal patterns

Functions: summary, head, size, jsonencode, anymissing, allfinite, ismissing, groupcounts, numunique, allunique, kde, corrcoef, pivot, unique, isregular, isuniform, retime

Read: exploration.md


Data Types

Use modern MATLAB types instead of legacy alternatives. Modern types are faster, more readable, and work better with table functions.

Topics:

  • Dates and times (parsing, arithmetic, timezones, extracting year/month/day/hour)

  • Elapsed time and calendar offsets

  • Text data (comparing, searching, splitting, editing strings)

  • Categorical data (ordinal rankings, merging/renaming/reordering levels)

Functions: datetime, dateshift, year, month, day, weekday, quarter, hour, timeofday, ymd, hms, hours, days, minutes, seconds, calmonths, caldays, string, matches, contains, startsWith, extractAfter, extractBefore, replace, erase, strip, split, count, categorical, mergecats, renamecats, removecats, reordercats, countcats

Read: data-types.md


Tables and Timetables

Tables are the primary container for tabular data. Use timetable when the data has timestamps, a time vector, or a known sample rate — it unlocks time-aware operations (automatic spacing-aware smoothing, filling, and resampling).

Topics:

  • Creating and structuring tables (variables vs rows, metadata, properties)

  • Selecting variables by type; dot indexing vs braces vs parentheses

  • Converting variable types after import

  • Working with non-uniformly spaced data (SamplePoints)

  • Resampling, aligning, and synchronizing time series

  • Filtering by date range or time tolerance

  • Converting legacy timeseries objects

Functions: table, timetable, table2timetable, vartype, convertvars, retime, synchronize, lag, timerange, withtol, timeseries2timetable, table2array, array2table

Read: tables-and-timetables.md


Eventtables

Use eventtable when tagging or annotating timetable rows with events, episodes, or phases (sensor anomalies, storms, maintenance windows, alarms). Do NOT add boolean columns, string labels, or categorical state variables to the timetable itself.

Topics:

  • Creating an eventtable from timestamps and labels (instantaneous or interval)

  • Attaching events to a timetable

  • Filtering timetable rows by event properties

  • Extracting events from patterns in data (peaks, threshold crossings)

  • Pushing event data into timetable rows for export or grouping

  • Automatic event overlays in plots

Functions: eventtable, eventfilter, extractevents, syncevents, withtol, stackedplot

Read: eventtables.md


Data Cleaning

Handle missing values and outliers using MATLAB's built-in detection and fill functions. Never compare with == for missing values. Use standardizeMissing to convert sentinel values before filling or removing.

Topics:

  • Detecting missing values (NaN, NaT, missing strings, undefined categoricals)

  • Converting placeholder values ("N/A", -999, "") to standard missing

  • Filling gaps (interpolation, forward-fill, moving window, per-type strategies)

  • Limiting fill across long gaps

  • Skipping missing values in aggregation (mean, std, min, max) — correct calling syntax

  • Detecting, removing, or replacing outliers

  • Checking whether values fall within an expected range; clamping

Functions: ismissing, anymissing, standardizeMissing, fillmissing, rmmissing, isoutlier, rmoutliers, filloutliers, isbetween, allbetween, clip

Read: data-cleaning.md


Data Transformation

Filter, sort, reshape, normalize, bin, join, and manage table variables. Use vectorized operations and built-in functions — not loops over rows or manual if-else chains.

Topics:

  • Filtering rows by condition or value range

  • Sorting and retrieving top/bottom N rows

  • Applying functions across rows or across variables

  • Renaming, reordering, adding, removing, splitting, merging variables

  • Converting types and applying in-place transforms

  • Binning continuous values into categories

  • Normalizing, scaling, z-scoring

  • Reshaping between wide and tall formats (pivot, stack, unstack)

  • Joining/merging tables on key variables

Functions: sortrows, topkrows, rowfun, varfun, convertvars, renamevars, movevars, addvars, removevars, splitvars, mergevars, discretize, normalize, clip, rescale, isapprox, isbetween, pivot, stack, unstack, rows2vars, innerjoin, outerjoin, join

Read: data-transformation.md


Grouping and Aggregation

groupsummary is the go-to for grouped statistics — not findgroups+accumarray or manual loops. Use groupfilter for per-group row filtering, grouptransform for per-group normalization, and pivot for cross-tabulation.

Topics:

  • Computing statistics by group (mean, sum, std, min, max, custom)

  • Binning on the fly (numeric edges, hourly/monthly/seasonal time bins)

  • Handling missing or empty groups

  • Filtering rows based on group-level conditions (e.g., minimum group size)

  • Removing per-group outliers

  • Normalizing within each group (z-score, rescale)

  • Cross-tabulating counts or aggregated values

Functions: groupsummary, groupcounts, groupfilter, grouptransform, pivot, findgroups

Read: grouping-and-aggregation.md


smoothdata is the unified entry point for smoothing (not smooth, which requires Curve Fitting Toolbox). Use detrend or trenddecomp for trend removal/decomposition, and islocalmax/islocalmin/ischange for pattern detection.

Topics:

  • Smoothing noisy data (moving average, Gaussian, Savitzky-Golay, median)

  • Choosing window size (element count vs duration for time-stamped data)

  • Removing linear or polynomial trends

  • Separating trend from seasonality (seasonal decomposition)

  • Finding peaks, valleys, and local extrema

  • Detecting abrupt changes in mean, variance, or slope

  • Summarizing distributions (bin counts, histograms)

Functions: smoothdata, movmean, movmedian, detrend, trenddecomp, islocalmax, islocalmin, ischange, histcounts, histogram

Read: smoothing-and-trends.md


Array and Grid Data

Use arrays when data is homogeneous numeric AND either naturally 2D/grid, performance-critical, or delivered by upstream tooling. For 2D grids, use dedicated 2D functions — do not loop 1D functions over rows/columns.

Topics:

  • When to stay in arrays vs converting to table

  • Operating along a specific dimension (row-wise vs column-wise)

  • Common pitfalls with dimension arguments in std, var, movstd, movvar

  • Handling NaN in array computations (not automatic)

  • Moving window and cumulative statistics

  • Padding, trimming, or resizing arrays to a target length

  • 2D spatial smoothing, gap filling, and peak detection on grids

  • Grouped operations using a grouping vector

Functions: smoothdata2, fillmissing2, islocalmax2, islocalmin2, paddata, trimdata, resize, mink, maxk, bounds, rms, prctile, quantile, iqr, cumsum, cummax, cummin, cumprod, movmean, movmedian, movsum, movstd, movvar, isuniform, isregular

Read: array-and-grid-data.md


Answering Questions About Data

When the task is answering a specific question about data (top-N, filtering, lookups, comparisons), read the strategies reference to avoid common mistakes with sorting direction, missing data, and value interpretation.

Topics:

  • Finding the highest/lowest/top/bottom N entries

  • Looking up values in one column based on ranking in another

  • Accounting for missing or placeholder values in answers

  • Returning raw data values without substitution or mapping

  • Counting rows that match a condition (exact vs partial text matching)

Functions: topkrows, sortrows, groupsummary, standardizeMissing, isapprox, matches, contains, height, nnz

Read: answering-data-questions.md


Copyright 2026 The MathWorks, Inc.

Files

references/array-and-grid-data.md

Array and Grid Data

Contents: when to use arrays, dimension-aware operations, std/var/movstd/movvar pitfall, missing data handling, moving and cumulative statistics, mink/maxk/bounds/rms, paddata/trimdata/resize, logical indexing, grouping on arrays, smoothdata2, fillmissing2, islocalmax2/islocalmin2

When arrays are appropriate (vs converting to table or timetable)

Arrays are the right container when data is homogeneous numeric AND either:

  • Naturally 2D/grid (sensor matrices, geospatial elevation/temperature grids, data gridded along x- and y-coordinates)

  • Vectorized numeric computation where all columns share the same type — operations on arrays are fully vectorized, whereas the same numeric data spread across table variables incurs per-variable overhead

  • Performance-critical inner loop where table overhead matters

  • Upstream tooling delivers arrays and conversion adds no value (MEX, toolbox output, legacy code)

Tables remain the default for mixed-type, labeled, or observational data. This section validates staying in arrays for legitimate cases — not as an excuse to avoid tables.

Converting between containers:

T = array2table(matrix, VariableNames=["X" "Y" "Z"]);
X = table2array(T(:,vartype("numeric")));

For table and timetable workflows, see tables-and-timetables.md.

Getting oriented with array data

size(X)                    % dimensions [rows, cols, ...]
ndims(X)                   % number of dimensions
anymissing(X)              % quick health check: any NaN?
summary(X)                 % per-column NumMissing, Min, Median, Max, Mean, Std (R2024b+)
summary(X,2,Statistics=["mean" "std" "nummissing" "range"])  % choose specific per-row stats (R2024b+)

% Per-column stats
mean(X)                    % column means (1-by-n)
[s,m] = std(X,0,1);        % column std AND mean in one call (m is the mean used internally)
[lo,hi] = bounds(X);       % column min and max in one call (1-by-n each)

% Per-row stats
mean(X,2)                  % row means (m-by-1)
[s,m] = std(X,0,2);        % row std AND mean in one call
[lo,hi] = bounds(X,2);     % row min and max (m-by-1 each)

Dimension-aware operations

For most array functions, the default operating dimension is the first non-singleton dimension — which is dim=1 for matrices but may differ for vectors or higher-dimensional arrays.

sum, mean, std, var, max, min, median collapse along the default dimension — for matrices this means collapsing rows, producing one value per column. To operate along a different dimension, specify it explicitly.

Other functions also accept a dimension argument but are not dim-reducing (e.g., rmmissing, fillmissing, cumsum, summary, etc). The pattern is the same: specify which dimension to operate along.

colMeans = mean(X);        % same as mean(X,1) — one value per column
rowMeans = mean(X,2);      % one value per row
allMean  = mean(X,"all");  % scalar — collapse all dimensions

% For multidimensional arrays, collapse multiple dimensions at once:
sliceMean = mean(X,[1 2]); % collapse dims 1 and 2, keep remaining dims
The std/var weight-first-arg pitfall

std and var take a weighting scheme w as the SECOND argument, not a dimension. The signature is std(X,w,dim) — to specify dimension, you must pass w first. Writing std(X,2) sets w=2, it does NOT compute std along dimension 2.

% CORRECT — compute std along dimension 2 (per-row)
rowStd = std(X,0,2);       % w=0 (default normalization), dim=2

% WRONG — this sets w=2 and operates along the default dimension
rowStd = std(X,2);          % NOT per-row std!

The w argument serves dual purposes:

  • 0 = unbiased estimate, normalizing by N-1 (sample std, default)

  • 1 = biased estimate, normalizing by N (population std)

  • A vector of nonneg values = actual weighted std (length must match the operating dimension)

The same applies to var:

rowVar = var(X,0,2);       % correct: per-row variance

Integer input (R2026b). var and std now accept integer inputs (int8, int16, int32, uint8, uint16, uint32) directly — the explicit double(...) cast previously required for integer data is no longer needed:

v = var(intData);          % intData is int16 — no double(intData) cast needed
s = std(intData,0,2);      % per-row std of integer data
Specifying dimension explicitly

When operating on matrices or multidimensional arrays, consider specifying the dimension if the input shape may vary or if dim=1 is not obvious from context. This makes intent clear and prevents surprises when data comes in as a row vs. a column. For straightforward cases where the default dimension is natural, omitting it is fine — MATLAB's defaults are designed to do the right thing for common usage patterns.

Missing value handling in array statistics

Array stats functions do NOT automatically skip NaN. Pass "omitmissing" explicitly — it works for numeric NaN and also for other missing-value types (datetime NaT, string missing, etc.):

m = mean(X,1,"omitmissing");           % column means, skipping NaN
s = std(X,0,1,"omitmissing");          % column std, skipping NaN
[lo,hi] = bounds(X,1,"omitmissing");   % bounds, skipping NaN

Missing data in arrays

Quick check
anymissing(X)              % scalar logical — any missing values?
sum(ismissing(X))          % count per column
sum(ismissing(X),2)        % count per row
Removing missing data with rmmissing
Xclean = rmmissing(X);              % remove rows with any missing
Xclean = rmmissing(X,2);            % remove columns with any missing
Xclean = rmmissing(X,1,MinNumMissing=3);  % only remove rows with 3+ missing values
Filling missing data (1D) with fillmissing

On arrays, the key difference from table usage is the dim argument for controlling direction. For fill methods, DataVariables, and MaxGap, see data-cleaning.md.

F = fillmissing(X,"linear");           % interpolate per column
F = fillmissing(X,"linear",2);         % interpolate along dim 2 (across columns)
Filling missing data (2D) with fillmissing2

Use fillmissing2 for 2D grids — it treats the matrix as a bivariate surface and interpolates using spatial information from both dimensions. Do not loop fillmissing over rows/columns for grid data.

F = fillmissing2(X,"linear");                     % 2D linear interpolation
F = fillmissing2(X,"natural");                    % natural neighbor interpolation
F = fillmissing2(X,"cubic");                      % cubic interpolation
F = fillmissing2(X,"movmedian",{3,3});            % 3x3 moving median fill

SamplePoints for non-uniform grids — 2-element cell array {xCoords, yCoords}, one vector per dimension. The cell array allows different types per dimension (e.g., duration for time, numeric for space):

F = fillmissing2(X,"linear",SamplePoints={lon,lat});
% mixed types, moving window maps to SamplePoints
F = fillmissing2(X,"movmedian",{hours(2),5},SamplePoints={hours(1:nCols),1:nRows});  

MissingLocations — use when you already have a logical mask identifying values to treat as missing (e.g., from a prior detection step). If you need to convert sentinel values like -999 to standard missing, use standardizeMissing first instead:

F = fillmissing2(X,"natural",MissingLocations=badMask);

Available interpolation methods: "nearest", "linear", "natural", "cubic", "v4" (biharmonic spline). Moving window methods: "movmean", "movmedian".

Moving and cumulative statistics

Moving window operations (1D, per column or per row)

These operate on 1D slices of the array — one column or one row at a time. For 2D grid smoothing, see smoothdata2 below. The options below ([kb kf], "omitmissing", EndPoints, SamplePoints) apply to all mov* functions: movmean, movmedian, movsum, movstd, movvar, movmad, movprod, movmin, movmax.

M = movmean(X,5);              % 5-element moving mean per column
M = movmedian(X,7,2);          % 7-element moving median per row (along dim 2)
M = movsum(X,10);              % 10-element moving sum per column
M = movmad(X,5);               % moving median absolute deviation per column

% Asymmetric (trailing) window: [kb kf] = elements before + after current
M = movmean(X,[4 0]);          % trailing 5-point average (current + 4 preceding)
M = movmedian(X,[0 4]);        % leading 5-point median (current + 4 following)

% Missing value handling
M = movsum(X,5,"omitmissing"); % skip NaN in computation

% Endpoint handling
M = movmean(X,5,EndPoints="discard");   % omit values where window doesn't fully overlap
M = movmedian(X,5,EndPoints="fill");    % NaN where window is incomplete
M = movmean(X,5,EndPoints=0);           % substitute 0 for missing boundary elements

% Non-uniform spacing
M = movmean(X,hours(2),SamplePoints=t); % window in sample-point units (t is datetime/duration)
The movstd/movvar weight-first-arg pitfall

movstd and movvar have the same pitfall as std/var: the third positional argument is a normalization weight, NOT a dimension. To specify dimension, pass weight as the third arg and dimension as the fourth.

% CORRECT — moving std along dimension 2 (across columns)
M = movstd(X,k,0,2);       % window=k, weight=0 (N-1), dim=2

% WRONG — this sets weight=2, does NOT operate along dim 2
M = movstd(X,k,2);          % third arg is weight, not dim!

% Population-normalized moving std (weight=1 means normalize by N)
M = movstd(X,k,1,1);       % window=k, weight=1 (N), dim=1

% More examples
M = movstd(X,5,0,1);       % window=5, sample std, per column
M = movvar(X,5,0,2);       % window=5, sample var, per row

Second output: the moving mean (R2026b). Like std/var (which return the mean as a second output — see "Getting oriented" above), movstd and movvar can return the moving mean used in the computation as a second output — no separate movmean call needed:

[M,MM] = movstd(X,k,0,2);   % M = moving std, MM = moving mean (both along dim 2)
[V,MM] = movvar(X,k);       % V = moving var, MM = moving mean (per column)
Cumulative operations
C = cumsum(X);                      % running sum per column
C = cumsum(X,2);                    % running sum per row
C = cumsum(X,"reverse");            % running sum from end to start (right-to-left / bottom-to-top)
C = cumsum(X,2,"reverse");          % reverse along dim 2
C = cummax(X);                      % running maximum per column
C = cummin(X,2);                    % running minimum per row
C = cumprod(X,"omitmissing");       % running product, skipping NaN

Direction ("forward"/"reverse") and "omitmissing"/"includemissing" apply to cumsum, cummax, cummin, and cumprod.

Single-value statistics
[lo,hi] = bounds(X);                  % min and max per column
[lo,hi] = bounds(X,2);                % min and max per row
[lo,hi] = bounds(X,"all");            % global min and max
B = mink(X,3);                        % 3 smallest per column
B = mink(X,3,2);                      % 3 smallest per row
[B,I] = maxk(X,5);                    % 5 largest per column with indices
r = rms(X);                           % root mean square per column
r = rms(X,2);                         % root mean square per row
r = rms(X,1,"omitmissing");           % skip NaN (base MATLAB since R2022a)

prctile, quantile, and iqr are base MATLAB (since R2022a) — no Statistics Toolbox required:

p = prctile(X,[25 50 75]);            % percentiles per column
p = prctile(X,[25 50 75],2);          % percentiles per row
q = quantile(X,4);                    % quartile boundaries per column
r = iqr(X);                           % interquartile range per column
r = iqr(X,2);                         % interquartile range per row

Resizing and alignment

Use paddata, trimdata, and resize (R2023b) instead of manual indexing or NaN concatenation.

% Pad to target length (default: trailing zeros along first non-singleton dim)
B = paddata(X,100);                        % pad to 100 rows
B = paddata(X,100,FillValue=NaN);          % pad with NaN
B = paddata(X,100,Side="leading");         % prepend instead of append
B = paddata(X,100,Dimension=2);            % pad columns instead of rows
B = paddata(X,1024,Pattern="edge");        % extend by repeating boundary values

% Trim to target length (default: remove trailing)
B = trimdata(X,50);                        % trim to 50 rows
B = trimdata(X,50,Side="leading");         % trim from beginning
B = trimdata(X,50,Dimension=2);            % trim columns

% Resize — pads or trims as needed to hit exact target
B = resize(X,100);                         % single dimension
B = resize(X,[100 8],Dimension=[1 2]);     % target both dimensions

Note: the dimension argument for paddata, trimdata, and resize is a name-value (Dimension=), unlike most stats functions where it is positional.

Padding patterns for paddata and resize:

PatternBehavior
"constant" (default)Fill with zeros (or custom FillValue)
"edge"Repeat the last element
"circular"Wrap around (periodic extension)
"flip"Mirror without repeating boundary
"reflect"Mirror including boundary element

Side options: "trailing" (default), "leading", "both".

These functions also work on tables, timetables, cell arrays, and structure arrays.

Checking uniform spacing

Use isuniform for numeric vectors and isregular for datetime/duration vectors and timetables:

[tf,step] = isuniform(t);      % numeric vectors — step returned as double
[tf,step] = isregular(TT);     % timetables, datetime, duration — step returned as duration or calendarDuration

These are not interchangeable — subtle differences exist:

  • isuniform returns true when spacing is zero (e.g., isuniform([1 1 1]) is true); isregular returns false for zero spacing

  • The second output of isuniform is always a double, regardless of input type

  • isuniform errors if the computed step exceeds realmax

Verify uniform spacing before operations that require it (e.g., trenddecomp, FFT-based analysis). Also covered in exploration.md.

Logical indexing and filtering

Index with logical masks directly — this is cleaner and more performant than find. Use find only when you specifically need the numeric indices (e.g., for reporting positions or non-contiguous assignment).

Floating-point pitfall: Do not use == to compare computed numeric values — floating-point arithmetic introduces round-off error. Use isapprox (R2024b) for tolerance-aware comparison:

mask = isapprox(X(:,3), 1.5);                  % approximate equality (default tol ~1e-15)
mask = isapprox(X(:,3), 1.5, "loose");          % wider tolerance (~1e-8)
mask = isapprox(X(:,3), target, RelativeTolerance=1e-6);  % custom relative tolerance
% Preferred: logical indexing
mask = X(:,3) > 100;                   % rows where column 3 exceeds 100
subset = X(mask,:);                     % extract matching rows

% Combine conditions
mask = X(:,1) > 0 & X(:,2) < 50;
subset = X(mask,:);

% any/all along dimensions
rowsWithNaN = any(ismissing(X),2);      % logical column: true if row has any missing
colsAllPositive = all(X > 0,1);         % logical row: true if column is all positive

% find — use ONLY when you need the actual index values
[row,col] = find(X == max(X,[],"all")); % subscript location of global maximum
idx = find(X(:,1) > threshold, 1);      % index of first row exceeding threshold

Grouping on arrays

groupsummary, grouptransform, and groupfilter work on arrays — the syntax uses a grouping vector instead of a variable name. For table syntax, see grouping-and-aggregation.md.

groupsummary on arrays
% Basic: summarize X by groups defined in g
[grpMeans,grpIDs,grpCounts] = groupsummary(X,g,"mean");

% Multiple methods
[result,grpIDs,grpCounts] = groupsummary(X,g,["mean" "std"]);

% With binning (bin the grouping variable)
[result,grpIDs,grpCounts] = groupsummary(X,g,[0 10 20 30 Inf],"mean");

% Multiple grouping vectors
[result,grpIDs,grpCounts] = groupsummary(X,{g1,g2},"sum");

Key difference from table syntax: the method argument is required for arrays (tables can omit it to get counts only). Additionally, array syntax has multiple outputs to hold results, group ids and group counts, rather than one table holding all the information.

grouptransform on arrays
B = grouptransform(X,g,"zscore");          % per-group z-score
B = grouptransform(X,g,"rescale");         % per-group rescale to [0,1]
B = grouptransform(X,g,"meanfill");        % fill NaN with group mean

Available methods: "zscore", "norm", "meancenter", "rescale", "meanfill", "linearfill", or a function handle.

groupfilter on arrays
B = groupfilter(X,g,@(x) size(x,1) >= 5);   % keep groups with 5+ members
B = groupfilter(X,g,@(x) ~isoutlier(x));    % remove per-group outliers

2D smoothing with smoothdata2

Use smoothdata2 for 2D grids — do not loop smoothdata over rows/columns. It treats the matrix as a surface and smooths in both directions simultaneously. For 1D smoothing details, see smoothing-and-trends.md.

S = smoothdata2(X,"movmean");                     % automatic window
S = smoothdata2(X,"gaussian",{5,5});              % 5-by-5 Gaussian window
S = smoothdata2(X,"movmedian",{3,7});             % 3 rows by 7 columns

Available methods: "movmean" (default), "movmedian", "gaussian", "lowess", "loess", "sgolay".

Window specification:

  • Scalar k: symmetric k-by-k window

  • Cell array {m,n}: m-by-n block

  • Cell array {[bRow fRow],[bCol fCol]}: asymmetric (preceding/following per dimension)

SamplePoints for non-uniform grids — 2-element cell array {xCoords, yCoords}. The cell array allows different types per dimension (e.g., duration for time, numeric for space):

S = smoothdata2(X,"gaussian",SamplePoints={lon,lat});
S = smoothdata2(X,"movmean",SamplePoints={hours(1:nCols),1:nRows});

2D detection with islocalmax2 / islocalmin2

Use islocalmax2 for peak detection in 2D grids (elevation, temperature, pressure). It examines a 2D neighborhood — do not flatten or loop. For 1D peak detection, see smoothing-and-trends.md.

TF = islocalmax2(X);                              % local maxima in 2D
TF = islocalmax2(X,MinProminence=10);             % ignore small bumps
TF = islocalmax2(X,MaxNumExtrema=5);              % top 5 most prominent peaks
TF = islocalmax2(X,MinSeparation=3);              % minimum Euclidean distance apart
[TF,P] = islocalmax2(X);                          % also get prominence values
TF = islocalmin2(X,MinProminence=10);             % 2D valleys (same options)

Key name-value arguments (same for both islocalmax2 and islocalmin2):

  • MinProminence — minimum prominence threshold (default: 0). Increase for noisy data.

  • MaxNumExtrema — return only the N most prominent peaks

  • MinSeparation — minimum Euclidean distance between peaks

  • FlatSelection — how to handle plateaus: "center" (default), "first", "all"

  • ProminenceWindow — restrict prominence calculation region: scalar k for k-by-k, {m,n} for rectangular

  • SamplePoints — 2-element cell array {xCoords, yCoords} for non-uniform grids


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.

Needs: Needs an API key

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/matlab-data-import-and-analysis/matlab-analyze-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-analyze-data.zip