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/tables-and-timetables.md

Tables and Timetables

Contents: table/timetable basics, variable naming, metadata, vartype, indexing, convertvars, SamplePoints, ReplaceValues, retime, synchronize, lag, timerange, timeseries2timetable, eventtable, table2array

Use table/timetable as primary data containers for tabular data

T = table(dates,values,categories, ...
    VariableNames=["Date" "Value" "Category"]);

% Avoid: Arrays lose context
data = [datenum(dates) values double(categories)];

Table design: variables are homogeneous, rows are observations

Each variable (column) should contain values of the same type, units, and meaning. Each row is one observation. If data arrives transposed (measurements as rows, subjects as columns), restructure with rows2vars or rebuild the table:

% Recommended: observations as rows, measurements as variables
T = table(["Bill";"Sue";"Jane"], [72;64;67], [180;130;135], ...
    VariableNames=["Name" "Height" "Weight"]);

% Not recommended: subjects as columns, measurements as rows
% (mixes types within a variable, breaks grouping/filtering)

Set meaningful table variable names

Terminology: Use "variable" (not "column") when referring to table data. A table variable can itself be multi-column (e.g., a matrix) or even a nested table — the only requirement is consistent row count. MathWorks documentation uses "variable" throughout; general internet usage often says "column" but this can be misleading for multi-column variables.

T.Properties.VariableNames = ["OrderDate" "CustomerID" "TotalAmount" "Region"];

% Avoid: Generic names
T.Properties.VariableNames = ["Var1" "Var2" "Var3" "Var4"];

Organize metadata in table properties

Store per-variable metadata in Properties — not as extra data rows or separate lookup tables:

T.Properties.VariableNames = ["OrderDate" "CustomerID" "TotalAmount" "Region"];
T.Properties.VariableUnits = ["" "" "USD" ""];
T.Properties.VariableDescriptions = [...
    "Date of order" ...
    "Unique customer identifier" ...
    "Total order amount in US dollars" ...
    "Geographic sales region"];

Use CustomProperties for domain-specific per-variable metadata beyond units and descriptions:

T = addprop(T,"Source",["variable"]);
T.Properties.CustomProperties.Source = ["ERP" "CRM" "ERP" "CRM"];

Per-row metadata (operator name, equipment ID, batch number) belongs as additional table variables — not in Properties, which is per-variable only:

T.Operator = ["Alice"; "Bob"; "Alice"; "Carol"];
T.EquipmentID = ["EQ-01"; "EQ-02"; "EQ-01"; "EQ-03"];

Prefer DataVariables/vartype over column-by-column loops

It is rarely better to use a for loop to iterate over table variables. MATLAB's table functions operate on multiple variables at once via DataVariables and vartype — prefer these over column-by-column loops:

% Recommended: operate on multiple variables at once
T = fillmissing(T,"linear", DataVariables=vartype("numeric"));
T = normalize(T, DataVariables=vartype("numeric"));
T = smoothdata(T,"movmean",5, DataVariables=["Sensor1" "Sensor2" "Sensor3"]);

% Recommended: chain multiple preprocessing steps — each call handles all target variables
vars = ["Temp" "Pressure" "Flow" "Vibration"];
T = fillmissing(T,"linear", DataVariables=vars);
T = filloutliers(T,"linear","movmedian",25, DataVariables=vars);
T = smoothdata(T,"movmean",5, DataVariables=vars);

% Avoid: wrapping a multi-step pipeline in a loop over variables
for v = vars
    T.(v) = fillmissing(T.(v),"linear");
    T.(v) = filloutliers(T.(v),"linear","movmedian",25);
    T.(v) = smoothdata(T.(v),"movmean",5);
end

Use vartype for type-based selection

% Select by type
numericVars = T(:,vartype("numeric"));
textVars = T(:,vartype("string"));

Use appropriate table indexing

% Use dot notation for a single variable
col = T.Value;

% Use parentheses for table subsets
subset = T(:,["A" "B" "C"]);

% Use table2array when extracting as array
matrix = table2array(T(:,vartype("numeric")));

Use variable names not numeric indices

value = T.Value;
T.OldVar = [];

% Dynamic dot indexing when you have an index or computed name
val = T.(3);                    % access 3rd variable by index
val = T.(varName);              % access variable by name in a string variable

% Braces for extracting multiple variables as an array
matrix = T{:,[2 4 5]};         % extract variables 2, 4, 5 as array

% Avoid: Hardcoded numeric indices or workarounds through Properties
value = T{:,3};
T(:,5) = [];
name = T.Properties.VariableNames(ind); T(:,name);  % unnecessary indirection

Use dynamic dot indexing T.(expr) for runtime variable access

% Iterating over variables by index
for i = 1:width(T)
    T.(i) = fillmissing(T.(i),"previous");
end

% Variable name stored in a string
varName = "Salary";
vals = T.(varName);

% Computed or non-identifier names
T.("Net Income") = T.("Revenue") - T.("Total Cost");
colName = "Var_" + string(year(datetime("today")));
T.(colName) = zeros(height(T),1);

% Passing variable names to functions
function result = processColumn(T, varName)
    result = normalize(T.(varName));
end

Never use eval for dynamic variable access:

% Avoid: eval is slow, error-prone, and defeats static analysis
val = eval("T." + varName);           % WRONG
eval("T." + varName + " = x;");       % WRONG

Use convertvars or VariableTypes to fix variable types after import

Post-import type conversion is extremely common. Use convertvars for targeted fixes or set VariableTypes for bulk inspection and conversion:

% Convert specific variables by name
T = convertvars(T,["Region" "Status"],"categorical");
T = convertvars(T,"ID","string");

% Convert by type - e.g., all cellstr variables to string
T = convertvars(T,vartype("cellstr"),"string");

% Inspect current types
T.Properties.VariableTypes
%   "double"    "string"    "categorical"    "datetime"

% VariableTypes is also writeable - a shortcut for type conversion
T.Properties.VariableTypes("Status") = "categorical";

convertvars is not limited to type conversion: convertvars(t, vars, dataType) accepts function handles for both vars and dataType, letting you select variables by a predicate vartype can't express and apply a function in place - including functions that don't accept tables directly. See "Use convertvars for type conversion and in-place transforms" in data-transformation.md.

SamplePoints for non-uniform data

Many data preprocessing functions - fillmissing, isoutlier, smoothdata, and others - support a SamplePoints parameter for non-uniformly spaced data. The behavior depends on the container type:

Prefer operating on the whole table/timetable rather than extracting a single variable. This keeps the sample points paired with the data, and variables you aren't working on won't be touched.

Data must be sorted by the sample points in ascending order. Sort the table or timetable first with sortrows before calling any function that uses SamplePoints or timetable row times.

Table input: Set SamplePoints to the variable name representing the x-axis, and use DataVariables to target specific variables:

T = sortrows(T,"Distance");  % SamplePoints must be ascending
T = fillmissing(T, "linear", DataVariables="Value", SamplePoints="Distance");
T = smoothdata(T, "movmean", 50, DataVariables="Value", SamplePoints="Distance");
idx = isoutlier(T, DataVariables="Value", SamplePoints="Distance");

Timetable input: The row times are used as sample points automatically. Do not set SamplePoints - it will error:

TT = sortrows(TT);  % ensure sorted by row times
TT = fillmissing(TT, "linear", DataVariables="Value");
TT = smoothdata(TT, "movmean", hours(6), DataVariables="Value");
idx = isoutlier(TT, DataVariables="Value");

This is one of the key benefits of converting to timetable: all these functions become spacing-aware with no extra arguments.

See also smoothing-and-trends.md and data-cleaning.md for how SamplePoints affects window sizes and fill behavior.

ReplaceValues for non-destructive operations

Many preprocessing functions overwrite table/timetable variables by default. Set ReplaceValues=false to append results as new variables instead (e.g., "Value_filled", "Temp_smoothed"). See data-transformation.md for the full list of supporting functions and examples.

Construct timetables from a sample rate or time step

When data is uniformly sampled, use SampleRate or TimeStep instead of constructing an explicit time vector. The timetable stores only the step and start time — row times are computed on demand, using less memory:

% From sample rate (Hz) — row times are durations starting at 0
TT = timetable(sensorData, SampleRate=1000);

% From time step + absolute start time — row times are datetimes
TT = timetable(sensorData, TimeStep=seconds(0.001), StartTime=datetime(2024,1,1));

Timetable row times dimension name

The row times dimension name defaults to "Time" but inherits from the workspace variable name used during construction:

TT = timetable(hours(1:5)', x);                     % dimension name is "Time" (default)
TT = timetable(myTimes, x);                         % dimension name is "myTimes"
TT = table2timetable(T, RowTimes="Timestamp");      % dimension name is "Timestamp"
TT.Properties.DimensionNames{1}                     % check the actual name

This matters when referencing row times by name in groupsummary, sortrows, or other functions. Always use the actual dimension name rather than assuming "Time".

Timetables support numeric row times for non-time axes (R2026b)

Row times are no longer restricted to datetime/duration — a timetable can use a numeric (double or single) vector as its row times, so you can index by a unit-agnostic quantity such as distance or depth rather than clock time. A plain numeric subscript still selects by position, so use the labels subscripting helper to indicate that the contained numeric values are row-time subscripts rather than positional indices:

TT = timetable(temperature, RowTimes=depth);   % depth (double, e.g. metres) as row times
TT(100,:)                    % positional: the 100th row
TT(labels(100),:)            % row-time subscript: the row where depth == 100
TT(timerange(100,inf),:)     % row-time range: rows with depth > 100

The spacing-aware preprocessing benefits of timetables (retime, fillmissing, smoothdata, ...) still apply along the numeric axis.

Use retime to resample timetables, not manual interpolation

TThourly = retime(TT,"hourly","linear");

% Aggregation
TTdaily = retime(TT,"daily","mean");
TTmonthly = retime(TT(:,"Loss"),"monthly","sum");

% Custom time vector
newTimes = datetime(2024,1,1):hours(6):datetime(2024,12,31);
TTresampled = retime(TT,newTimes,"pchip");

Pitfall: retime does not support DataVariables. Aggregation methods must be applicable to all variables in the timetable. For example, exclude text-based variables before applying a "sum" aggregation. Select the variables you need first:

% Select specific variables
TTmonthly = retime(TT(:,"Loss"),"monthly","sum");

% Or select all numeric variables
TTmonthly = retime(TT(:,vartype("numeric")),"monthly","sum");

Per-variable behavior with VariableContinuity: To apply different methods to different variables, set the VariableContinuity property and call retime without a method. Each variable is resampled according to its continuity type:

TT.Properties.VariableContinuity = ["step" "continuous" "continuous" "step" "step"];
TTresampled = retime(TT,"monthly");
% "continuous" variables → linear interpolation
% "step" variables → previous value (forward fill)
% "event"/"unset" → filled with missing

Time steps: "yearly", "quarterly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", a custom datetime vector, or "regular" with a custom duration via TimeStep:

TT_6h = retime(TT(:,vartype("numeric")), "regular", "mean", TimeStep=hours(6));

Methods by category:

  • Interpolation: "linear", "spline", "pchip", "makima" - for upsampling to a finer grid

  • Aggregation: "mean", "median", "sum", "prod", "min", "max", "mode", "count", "firstvalue", "lastvalue", or a function handle (e.g., @std) - for downsampling to a coarser grid

  • Fill: "previous", "next", "nearest", "fillwithmissing", "fillwithconstant"

Interpolation and fill methods require sorted row times (for both retime and synchronize). Use sortrows(TT) first if row times may be unsorted. Aggregation methods do not require sorted row times.

Use retime to resolve duplicate timestamps

When a timetable has rows sharing the same timestamp (e.g., merged sensor logs), use retime with the unique row times to consolidate:

TT = retime(TT, unique(TT.Time), "firstvalue");

This preserves the original time spacing — unlike resampling to a regular grid, which changes it. Consider the structure and meaning of the data when choosing an aggregation method (e.g., "mean" for numeric measurements, "firstvalue" for mixed-type tables), and ensure the method is valid for all variables in the timetable.

Use synchronize to align multiple timetables

TTsync = synchronize(TT1,TT2,"intersection");

% With interpolation for missing times
TTsync = synchronize(TT1,TT2,"union","linear");

% Common regular time base
TTsync = synchronize(TT1,TT2,"hourly","mean");

synchronize supports the same time steps and methods as retime (interpolation, aggregation, and fill).

Use lag to time-shift timetable data

Pitfall: lag requires a regular (uniformly spaced) timetable — it errors on irregular spacing. Use retime to regularize first if needed.

TT_prev = lag(TT,1);              % shift data forward by 1 time step (previous values)
TT_next = lag(TT,-1);             % shift backward (next values)
TT_shifted = lag(TT,calmonths(2)); % shift by a calendar duration

% Compute row-to-row differences
TT_prev = lag(TT,1);
TT.Diff = TT.Value - TT_prev.Value;

Use timerange for time-based filtering

S = timerange("2024-01-01","2024-06-01");
TTsubset = TT(S,:);

% Open/closed boundaries (default is "openright": start <= t < end)
S = timerange("2024-01-01","2024-12-31","closed");

timerange works as a row subscript for any timetable - cleaner than logical indexing with isbetween on the time variable.

Time-based subscripting for timetables

Timetables support subscripting directly with datetime values, timerange, and withtol:

% Exact time subscript (returns empty timetable if no match)
row = TT(datetime(2024,3,15),:);

% Time range subscript (all rows in interval)
subset = TT(timerange("2024-01-01","2024-06-01"),:);

% Fuzzy match within tolerance (for irregular timestamps)
subset = TT(withtol(targetTimes,seconds(5)),:);

Prefer these over logical indexing with isbetween for timetables — they are more concise and purpose-built. Use isbetween for tables, which do not support time-based subscripting.

Consider timeseries2timetable for legacy timeseries objects

TT = timeseries2timetable(ts);

The timeseries class still works, but the modern timetable is recommended. Converting unlocks retime, synchronize, fillmissing, smoothdata, and other modern operations.

Use eventtable to annotate timetables with events

An eventtable stores labeled events (instantaneous or interval) that can be attached to a timetable:

% Create an eventtable from times and labels
ET = eventtable(datetime(2024,3,[1 5 12])', ...
    EventLabels=categorical(["Outage" "Maintenance" "Outage"]));

% With durations
ET = eventtable(datetime(2024,3,[1 5 12])', ...
    EventLabels=categorical(["Outage" "Maintenance" "Outage"]), ...
    EventLengths=hours([2 4 1]));

% Attach to a timetable
TT.Properties.Events = ET;

% Filter timetable at event times
EF = eventfilter(TT);
vals = TT(EF,:);

% Propagate event data into timetable rows
TT = syncevents(TT,EventDataVariables="EventLabels");

stackedplot automatically overlays attached events on time series plots.

Pass tables directly to math and chart functions when supported

Many math operations (sin, cos, abs, log, exp, mean, std, sum, min, max) and chart functions (plot, stackedplot, scatter) accept tables directly — this preserves variable names as labels and is faster than indirect alternatives. Pass the table directly to the math function — use mean(T(:,vars)) or std(T), not varfun(@mean,T) or T{:,:} extraction. Only extract to array for functions that truly require it (e.g., eig, svd).

% Recommended: pass table directly to math functions
m = mean(T(:,vartype("numeric")));
s = std(T(:,["Height" "Weight"]));

% Avoid: varfun wrapping (slower, less readable, same result)
m = varfun(@mean, T, InputVariables=vartype("numeric"));

% Avoid: extracting to array (loses variable names and metadata)
m = mean(T{:,vartype("numeric")});
% Recommended: keep data in the timetable throughout preprocessing
TT = fillmissing(TT,"linear", DataVariables=vartype("numeric"));
TT = smoothdata(TT,"movmean",25, DataVariables=vartype("numeric"));
TT = detrend(TT, DataVariables=vartype("numeric"));

% Avoid: extracting to array up front, then processing on the array
data = TT{:,vartype("numeric")};      % loses variable names, time info
data = fillmissing(data,"linear");
data = smoothdata(data,"movmean",25);
data = detrend(data);

Scalar arithmetic on tables and timetables (R2026b)

Scalar arithmetic operators apply directly to a table/timetable (R2026b). You can now use *, /, and \ on a table or timetable whose other operand is a scalar (mtimes/mrdivide/mldivide) — no data extraction needed. The scalar is applied to every variable and the variable names are preserved:

Tpercents = T * 100;       % convert fractional values to percentages
Thalf     = T / 2;         % halve every variable

% Avoid — extracting to array for a simple scalar operation
T{:,:} = T{:,:} * 100;             % unnecessary brace indexing
T2 = array2table(table2array(T) / 2, VariableNames=T.Properties.VariableNames);  % unnecessary round-trip

Only a scalar is supported as the other operand; for element-wise math against another array, operate per variable or extract to an array.

Use table2array when you need a numeric array

% Extract numeric data as an array (e.g., for functions that require arrays)
numericData = table2array(T(:,vartype("numeric")));

% The reverse
T = array2table(matrix, VariableNames=["X" "Y" "Z"]);

Note: Many plotting and analysis functions now accept tables directly — only convert to array when the function requires it. If your data is already in arrays and naturally 2D/grid (sensors, geospatial), see array-and-grid-data.md for array-native workflows.


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