Matlab Analyze Data
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Data and AI
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a 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
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/matlab/matlab-analyze-data/downloadUnzip 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-chartinstead)The task is purely symbolic math, simulation, or app building
Reading or writing files — CSV, Excel, Parquet, MAT-file (use
matlab-import-export-datainstead)Data doesn't fit in memory or requires out-of-core processing (use
matlab-choose-big-data-solutioninstead)Storing or retrieving passwords, tokens, or API keys (use
matlab-secure-credentialsinstead)Data lives in a relational database (use
matlab-use-databaseormatlab-use-duckdbinstead)Building an ML training pipeline from labeled signal files (use
matlab-prepare-signal-datainstead)Training classifiers or comparing ML model accuracy on tabular data (use
matlab-classify-tabular-datainstead)Engineering or selecting features to optimize a supervised ML model (use
matlab-engineer-tabular-featuresinstead)Code migration or replacing deprecated APIs (use
matlab-modernize-codeinstead)
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:
| Function | Available From | Purpose |
|---|---|---|
paddata, trimdata, resize | R2023b | Pad, trim, or resize arrays to target length |
smoothdata2 | R2023b | Smooth 2-D gridded data over rectangular windows |
kde | R2023b | Kernel density estimate for univariate data |
clip | R2024a | Clamp values to a range |
islocalmax2, islocalmin2 | R2024a | Detect local extrema in 2-D gridded data |
summary (enhanced) | R2024b | Supports arrays (numeric, datetime, duration, logical); adds Statistics, DataVariables, Detail name-value args |
isapprox | R2024b | Tolerance-aware floating-point comparison (use instead of == for computed values) |
isbetween (numeric) | R2024b | Check elements within a numeric range |
numunique | R2025a | Count distinct values in a variable |
allbetween | R2025a | Validate all values are within a range |
allunique | R2025a | Validate 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
timeseriesobjects
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
Smoothing, Trends, and Patterns
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
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md13.0 KiB
- manifest.yaml492 B
- references/answering-data-questions.md4.8 KiB
- references/array-and-grid-data.md19.6 KiB
- references/data-cleaning.md10.5 KiB
- references/data-transformation.md13.4 KiB
- references/data-types.md9.8 KiB
- references/eventtables.md12.4 KiB
- references/exploration.md10.0 KiB
- references/grouping-and-aggregation.md11.3 KiB
- references/smoothing-and-trends.md8.4 KiB
- references/tables-and-timetables.md19.0 KiB
references/data-types.md
Data Types
Contents: datetime (+ component extraction, dateshift), duration, calendarDuration, string arrays (search, edit, extract), categorical (ordinal, mergecats/renamecats/removecats/reordercats)
MATLAB also provides dictionary, enumeration, and other container types not covered in detail here. This skill focuses on the types most commonly encountered in tabular data analysis.
Quick Reference: Modern vs Legacy Types
| Instead of | Use | Why |
|---|---|---|
datenum, datestr | datetime | Proper arithmetic, timezone support |
char, cellstr, strcmp | string, ==/matches | == for scalar, matches for vector comparison |
| Numeric codes or strings with few unique values | categorical | Self-documenting, works with grouping functions, memory-efficient |
Use datetime not serial date numbers
dt = datetime("2024-01-15");
dt2 = datetime("now");
dateString = string(dt,"yyyy-MM-dd"); % string() only needed for export or UI display
elapsed = dt2 - dt; % Returns duration type
% Timezone-aware
dt = datetime("now",TimeZone="America/New_York");
% Avoid: Serial date numbers
dn = datenum("2024-01-15");
dn2 = now;
dateString = datestr(dn,"yyyy-mm-dd");
elapsed = dn2 - dn; % The unit of this is not clear!Effective use of the datetime constructor
Set InputFormat, TimeZone, and Format as name-value arguments on the single
datetime(...) call — never as follow-up dt.TimeZone = ... / dt.Format = ... assignments.
The property names match the argument names, so build the value fully in one statement:
offsets = ["2024-03-15T09:30:00-05:00" "2024-03-15T14:00:00+00:00"];
% One call — parse, set the zone, and set the display format together
dt = datetime(offsets, ...
InputFormat="yyyy-MM-dd'T'HH:mm:ssZZZZZ", ...
TimeZone="America/Los_Angeles", ...
Format="yyyy-MM-dd HH:mm:ss zzz");
% Avoid: parse, then mutate in separate statements
dt = datetime(offsets,InputFormat="yyyy-MM-dd'T'HH:mm:ssZZZZZ");
dt.TimeZone = "America/Los_Angeles";
dt.Format = "yyyy-MM-dd HH:mm:ss zzz";Use a follow-up .TimeZone / .Format assignment only to restamp a datetime you did not just
construct.
Convert text timestamps with InputFormat, not manual/regex parsing. For any text-to-datetime
conversion, write an InputFormat that matches the pattern in the data. Any literal characters
(marker letters, custom separators) can be escaped inside single quotes:
% Custom "2024_day100" day-of-year format — the literal word "day" contains letters that
% collide with format tokens, so quote it; DDD then parses the day-of-year number
labels = ["2024_day100" "2024_day200" "2024_day365"];
dt = datetime(labels,InputFormat="uuuu_'day'DDD",Format="uuuu-MM-dd");
% Doubled slashes as literal separators
dates = ["15//03//2024" "16//03//2024"];
dt = datetime(dates,InputFormat="dd//MM//yyyy");Look up the correct format tokens with doc datetime.Format — common ones: yyyy/uuuu (year),
MM (month number) vs MMM/MMMM (month name), dd (day), DDD (day of year), HH (24-hour)
vs hh (12-hour), mm (minute), ss (second), QQQ (quarter), ZZZZZ (offset like -05:00),
zzz (zone abbreviation).
Manual text/regex parsing is only justified when (a) the data uses a token datetime does not
support, or (b) an InputFormat call errors or returns NaT on the real values.
Time standards (R2026b). By default a datetime has no associated time standard (TimeStandard="none"), so its interpretation depends on context. For leap-second-sensitive or domain-specific work (e.g. aerospace, astronomy, telecommunications), set the TimeStandard name-value argument to an explicit standard — International Atomic Time ("TAI") or Terrestrial Time ("TT"), with "UTC" and "simplifiedUTC" also supported:
t = datetime("now",TimeStandard="TT"); % set at construction (preferred)Like TimeZone and Format, TimeStandard is also a property — assign it directly (t.TimeStandard = "TAI";) only to restamp an existing datetime.
Extract datetime components
Pull out parts of a datetime for computed variables, filtering, or display. In these examples, T is a table with a Date variable of type datetime:
T.Year = year(T.Date);
T.Month = month(T.Date); % numeric (1-12)
T.MonthName = month(T.Date,"name"); % "January", "February", ...
T.Day = day(T.Date);
T.Weekday = weekday(T.Date); % numeric (1=Sunday)
T.Quarter = quarter(T.Date);
T.Hour = hour(T.Date);
T.TimeOfDay = timeofday(T.Date); % duration since midnight
% Split into multiple components at once
[y,m,d] = ymd(T.Date);
[h,m,s] = hms(T.Date);See data-transformation.md for filtering with isbetween.
Use dateshift to snap dates to calendar boundaries or find specific weekdays:
T.MonthStart = dateshift(T.Date,"start","month");
T.QuarterEnd = dateshift(T.Date,"end","quarter");
T.NextFriday = dateshift(T.Date,"dayofweek","Friday");Note: For grouping by time unit (e.g., hourly means, monthly totals), prefer the binning rules in groupsummary, pivot, etc. rather than creating a separate component column. See grouping-and-aggregation.md for examples.
Use duration and calendarDuration for time differences
Arithmetic on datetime values produces duration (fixed-length) or calendarDuration (calendar-aware) results:
% duration — fixed units (years, days, hours, minutes, seconds, milliseconds)
elapsed = hours(3) + minutes(45);
T.ResponseTime = T.EndTime - T.StartTime; % duration result
% calendarDuration — calendar-aware (months, years vary in length)
offset = calmonths(3) + caldays(15);
T.DueDate = T.StartDate + offset;Pin arithmetic to period ends with ArithmeticMethod (R2026b). By default, adding a calendarDuration preserves the day of the month when it exists. To keep results anchored to the end of the month or quarter instead, construct the calendarDuration with ArithmeticMethod="endofmonth" (or "endofquarter"):
% Month-end-aware offset: adding it lands on month ends (Jan 31 → Feb 28/29 → Mar 31 → ...)
offset = calendarDuration(0,1,0,ArithmeticMethod="endofmonth");
T.PeriodEnd = T.StartDate + offset;caldiff and between support the same end-of-period differencing, and isregular recognizes month-end/quarter-end row times as regular.
Use duration for fixed time periods (elapsed time, sensor intervals). Use calendarDuration when calendar boundaries matter (months and years have variable lengths due to leap years and DST).
Dual-purpose creation/extraction functions: years, days, hours, minutes, seconds, milliseconds both create durations from numbers and extract numbers from durations:
d = hours(2.5); % create: 2.5 hr duration
n = hours(d); % extract: 2.5 (numeric)
T.ElapsedHours = hours(T.ResponseTime); % convert duration variable to numericDisplay format: The Format property controls display without changing the underlying value:
d = hours(1) + minutes(30);
d.Format = "hh:mm:ss"; % displays as "01:30:00"
d.Format = "m"; % displays as "90 min"Use string arrays not character/cell arrays
names = ["Alice" "Bob" "Charlie"];
isMatch = names == "Bob"; % scalar comparison
isMatch = matches(names,"Bob"); % vector-safe comparison
fullName = firstName + " " + lastName;
parts = split(names,",");
% Avoid: Character/cell arrays
names = {'Alice', 'Bob', 'Charlie'};
isMatch = strcmp(names,'Bob');
fullName = strcat(firstName,' ',lastName);
parts = cellfun(@(x) strsplit(x,','), names, UniformOutput=false);String arrays support vectorized search, edit, and extraction functions:
% Search
hasEmail = contains(T.Contact,"@");
isValid = startsWith(T.ID,"PRD-");
n = count(T.Text,"error");
% Edit
T.Name = upper(T.Name);
T.Name = strip(T.Name); % remove leading/trailing whitespace
T.Code = erase(T.Code,"-"); % remove substrings
T.Status = replace(T.Status,"N/A","Unknown"); % replace substrings
% Extract and split
T.Domain = extractAfter(T.Email,"@");
T.First = extractBefore(T.FullName," ");
parts = split(T.Address,","); % split into columnsUse categorical not coded numbers or cell strings
T.Status = categorical(T.Status,[1 2 3],["High" "Medium" "Low"]);
highPriority = T(T.Status == "High",:);
T.Region = categorical(T.Region);
% Avoid: Numeric codes or low-cardinality strings for categories
T.Status = [1; 2; 1; 3];
T.Region = ["North"; "South"; "North"; "East"]; % few unique values - better as categoricalUse ordinal categorical for rankings and comparisons:
T.Priority = categorical(T.Priority, ...
["Low" "Medium" "High" "Critical"], Ordinal=true);
urgent = T(T.Priority >= "High",:);matches, startsWith, endsWith, and contains accept categorical input directly (R2026b). They test against the category names, so there is no need to convert a categorical variable back to string first:
isActive = matches(T.Status,"Active"); % T.Status is categorical — no string(T.Status)
hasPrefix = startsWith(T.Region,"North"); % operates on the category names directlyManage categories
Consolidate, rename, or reorder category levels:
% Merge rare or related categories into one
T.Region = mergecats(T.Region,["Northeast" "Southeast"],"East");
% Rename categories
T.Status = renamecats(T.Status,["Act" "Inact"],["Active" "Inactive"]);
% Remove unused categories (e.g., after filtering rows)
T.Category = removecats(T.Category);
% Reorder for display or plotting
T.Size = reordercats(T.Size,["Small" "Medium" "Large"]);
% Count occurrences per category
countcats(T.Status)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