
matlab-optimize-performance
Use when MATLAB code is too slow or the user wants it faster, or asks to profile it, find its hot line or where the time goes, count how many times a function runs, or benchmark or compare timings. Profiles before changing code (Sampling Profiler on R2026b+), checks the output against the original, and reports only measured speedups. Not for writing performance tests.
- Installs
- 101
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/matlab/matlab-agentic-toolkit --skill matlab-optimize-performance- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads matlab-optimize-performance automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
MATLAB Performance Optimization Workflow
Systematic 7-step workflow for finding and fixing performance bottlenecks in MATLAB code.
When to Use
- User asks to speed up MATLAB code, or to optimize it for execution time
- User wants to find why their MATLAB code is slow
- User has a function or script that takes too long to run
- User asks to benchmark or time MATLAB code in the current session (a one-off timing or an A/B of two versions)
- User wants to compare performance before and after a change
- User asks about MATLAB performance best practices
When NOT to Use
- Optimizing Simulink model simulation speed (use Simulink Profiler)
- Speeding code up by compiling it with MATLAB Coder (
codegen, MEX), or tuning generated MEX (use thematlab-generate-codeskill) - The problem is memory, not speed: out-of-memory errors or peak memory (use the
matlab-optimize-memoryskill) - The performance issue is purely I/O-bound (file reads, network, database)
- User wants to write performance tests, or track timings across builds or in CI (use the
matlab-write-performance-testsskill) - Note: for exact invocation counts, or a sub-10 ms / MEX / parallel workload, use the MATLAB profiler (
profile) rather than the Sampling Profiler (Step 2) — that's a profiler choice, not a reason to skip the skill
The 7-Step Workflow
Step 1: Establish Baseline
Measure current performance so you have a number to improve against:
f = @() targetFunction(input1, input2);
baseline = timeit(f); % handles warm-up and repeats; prefer it to tic/toc
For GPU code use gputimeit. For a script, run it once to warm up, then time a second run with tic/toc. Templates: assets/measurement-templates.md.
Step 2: Profile and Analyze
Find where the time actually goes — don't guess, profile.
Pick the profiler first: check, don't assume. In R2026b+ the Sampling Profiler is the default: a
low-overhead statistical profiler that samples the execution thread at ~100 Hz. This skill's
sampling_profiler helper drives it, and sampling_profiler('available') tells you whether this MATLAB
has it. Use the MATLAB profiler (profile) only when available is false, when you need exact call
counts, or for a one-shot call too short to loop, or MEX or parallel code.
% Sampling Profiler — use when sampling_profiler('available') is true (clean up after)
addpath(fullfile(skillRoot, "scripts")); % skillRoot = directory containing this SKILL.md
assert(sampling_profiler('available')); % false -> use the MATLAB profiler block below
nReps = 1; % raise until the loop below runs several seconds (~10 s is ideal)
sampling_profiler('on');
sampling_profiler('pause');
targetFunction(input1, input2); % warm-up: pays first-call cost, not collected
sampling_profiler('clear');
sampling_profiler('resume');
for r = 1:nReps, targetFunction(input1, input2); end
[~, stacks] = sampling_profiler('off');
sampling_profiler('destroy'); % mandatory cleanup: skipping it corrupts later runs
% MATLAB profiler — any release; use when the Sampling Profiler isn't available
profile on; targetFunction(input1, input2); profile off; profile viewer;
Reading the sampler:
- Run several seconds; ~10 s is ideal (~1000 samples; ~100 is the bare minimum). Loop a quick
workload by raising
nReps, and keep the warm-up call. If it can't be looped, useprofile. - The counts describe the profiled run (
stacks.TotalSamples/100is close to its wall clock) and include no invocation counts. For how many times something ran, useprofile, and record"call_count_source": "builtin_profile_numcalls","sampling_can_count_invocations": falseand"sampling_profiler_samples"inperf_report.json. - Neither profiler sees inside a builtin or P-coded frame: the time lands on the call site with no line detail. Confirm such a hotspot by removing it and re-timing (Step 5).
Work from the profile to a change:
- Rank functions by self time, then read the lines inside the top one. Per-line time includes callees, so a line that only makes a call can outrank the line doing the work.
- Before changing anything, say from the code why that line is slow: a real mechanism (a reallocation in a loop, a builtin on a large array), not just a big percentage.
- Step 5 is the proof: if re-timing doesn't move the clock, your explanation was wrong; profile again.
For the full Sampling Profiler API, results model, traps, and helpers, see references/sampling-profiler.md.
Step 3: Identify Optimization Opportunities
Based on profiling results, identify which patterns apply. Read references/optimization-patterns.md for the full catalog.
| Pattern | Typical Speedup | Look For |
|---|---|---|
| Vectorization | 2–200x | Loops doing element-wise math on arrays |
| Preallocation | 2–100x | Arrays growing inside loops (x = [x; newRow]) |
| Unnecessary recomputation | 2–50x | Same expensive expression computed multiple times |
discretize/histcounts | 2–50x | Loops binning or classifying data |
| Persistent caching | 1.5–95x | Repeated load() or expensive object creation |
| Logical indexing | 1.2–5x | Using find() just to index into an array |
arguments block | 1.1–1.8x | Functions using inputParser |
| Algebraic simplification | 1.5–3x | Redundant sqrt, abs, or matrix ops |
Before optimizing, verify the target is worth it:
- Is it called in a tight loop? High call count × small time = big total.
- Is it M-code or a built-in? You can't make a built-in faster, but you can often call it fewer times (e.g., pass a matrix to
filtfilt/filterinstead of looping over columns).
Step 4: Implement Optimizations
Apply the patterns from Step 3, starting with the highest-impact one. Before/after examples are in references/optimization-patterns.md.
- Move invariant work out of loops (object creation, option parsing, constant expressions)
- Replace element-wise loops with array operations where possible
- Use purpose-built functions (
discretize,cumsum,hypot) instead of hand-written equivalents - For large data, batch the vectorization to control memory (see Pattern 9 in catalog)
- Try each new variant on a small slice of the input first: a wrong orientation in implicit expansion can build a huge array
Step 5: Measure Optimized Performance
Quick check, while you are still iterating: re-time with timeit as in Step 1 and compare with the baseline. A speedup of 1.2x or more is considered significant; below that, measurement noise makes it hard to be confident the change helped.
Verified result — required whenever the user asks for a number to report, commit, or share, when they gave you a hypothesis about what is slow, or when two profilers disagree. Follow references/measurement-protocol.md in full:
- Measure the ceiling before optimizing — delete or hoist the suspected work, re-time end-to-end, and compute what fraction of total time it actually accounted for; profiler attribution has been observed to overstate it by more than 10x. (This removal-and-re-time step is called ablation, and is recorded as
adjudication_method: "removal_ablation".) - Correctness gate against the original in the same session, with a tolerance scaled to the output (
100*eps(max(abs(original(:))))), plus an independent witness statistic of the output. - Mutation test — perturb the input; the output must change. Catches code that is fast because it stopped doing the work.
- Interleaved paired timing, one session, N ≥ 5,
median(tb ./ to). Never compare across sessions or in sequential blocks — machine drift lands entirely on one arm. - Write
perf_report.json— every field from a variable a run of the current code computed, never a typed-in literal. Run each step in its own tool call andsaveits results to a.matas it finishes, so a fix to the report re-writes it from those files instead of re-running the steps.
The headline speedup_median is always end-to-end. A sub-kernel number goes in kernel_speedup. A refuted hypothesis is a result: report it with the honest speedup, including 1.0.
Step 6: Verify Correctness
Every optimization must produce the same results as the original:
original = originalFunction(input1, input2);
fast = optimizedFunction(input1, input2);
% Scale the tolerance to the output — a fixed 1e-10 is wrong in both directions
tol = 100 * eps(max(abs(original(:))));
maxErr = max(abs(original(:) - fast(:)));
fprintf('Max error: %.2e (tol %.2e)\n', maxErr, tol);
assert(isequal(isnan(original), isnan(fast)) && maxErr <= tol, 'Results differ beyond tolerance!'); % max skips NaN
For non-numeric outputs:
assert(isequal(original, fast), 'Results differ!');
Error at or below eps(max(abs(original(:)))) is floating-point reordering noise — acceptable; document it. Error orders of magnitude above it is a bug, however clean the algebra looked. Watch for catastrophic cancellation: an algebraically exact shortcut (e.g. the running-sums variance formula) can be dramatically faster and still wrong on data with a large mean offset. Subtract the mean first, then check the result against the tolerance again.
An error of exactly 0 proves nothing on its own. Also record an independent statistic of the optimized output (min(fast(:)), a checksum) — see references/measurement-protocol.md.
Step 7: Report Results
Report the baseline, the optimized time, the speedup (for each change and end to end), the max error, and the pattern applied. If you followed the verified-result protocol in Step 5, perf_report.json is the deliverable and this is its human-readable summary.
Key Rules
- Always profile before optimizing — never guess where the bottleneck is
- Measure the ceiling before you optimize — remove or hoist the suspect and re-time end-to-end; that difference, not the profiler's
%column, is the ceiling on what a rewrite can win (this step is ablation) - One change at a time — measure after each optimization to know what helped
- Verify correctness — every optimization must produce equivalent output, with a tolerance scaled to the output
- Report end-to-end — the headline number is the whole workload; a sub-kernel speedup is reported separately and labelled as such
- Every reported number comes from a variable — computed by a run of the current code, never typed in from memory
- 1.2x threshold — speedups below 1.2x are not reliably distinguishable from noise
- GPU timing — always
wait(gpuDevice)before and after timing GPU code - Use
timeit— it handles warmup and averaging; avoid rawtic/tocfor benchmarks - On R2026a,
clearwhat you profiled before you time anything — code run underprofileon R2026a stays ~100x slower for the rest of the session until youclearit, so a baseline taken after a profiled run flatters every "after" number. R2026a also has no Sampling Profiler.
Common Mistakes
| Mistake | Why It's Wrong | Do This Instead |
|---|---|---|
| Growing arrays in loops | Each append copies the entire array | Preallocate before the loop |
| Vectorizing huge arrays blindly | May exceed memory | Use chunked processing for large data |
| Assuming faster = correct | Bugs can make code fast (by skipping work) | Verify results match (Step 6) + mutation test |
Fixed assert(maxErr < 1e-10) | Rejects clean results on large-magnitude data; passes broken ones on small | Scale tolerance to the output: 100*eps(max(abs(original(:)))) |
| Quoting a sub-kernel speedup as the headline | 8x on 20% of runtime is ~1.2x end-to-end | Headline is end-to-end; kernel number reported separately |
| Manufacturing a win when the hypothesis was wrong | A refuted hypothesis is a valid result | Report speedup_median honestly, including 1.0 |
Reference Files
references/measurement-protocol.md— the verified-result protocol for Step 5 and everyperf_report.jsonfieldreferences/sampling-profiler.md— Sampling Profiler (R2026b+): commands, results model, traps, and thescripts/helper indexreferences/optimization-patterns.md— the pattern catalog, with before/after code and measured speedupsassets/measurement-templates.md— templates for atimeitbaseline, GPU timing, and a scaling testscripts/— MATLAB helpers for the Sampling Profiler;addpaththis folder to use them
Copyright 2026 The MathWorks, Inc.
FAQ
What does the matlab-optimize-performance skill do?
Use when MATLAB code is too slow or the user wants it faster, or asks to profile it, find its hot line or where the time goes, count how many times a function runs, or benchmark or compare timings. Profiles before changing code (Sampling Profiler on R2026b+), checks the output against the original, and reports only measured speedups. Not for writing performance tests.
How do I install matlab-optimize-performance?
Run npx skills add https://github.com/matlab/matlab-agentic-toolkit --skill matlab-optimize-performance in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/matlab-optimize-performance/ (personal) or .claude/skills/matlab-optimize-performance/ (project).
Which AI agents can use matlab-optimize-performance?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is matlab-optimize-performance safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains matlab-optimize-performance?
It is published by matlab in matlab/matlab-agentic-toolkit. It has 101 recorded installs.
More from matlab/matlab-agentic-toolkit
matlab-review-code
matlab/matlab-agentic-toolkit
Review MATLAB code for quality, performance, maintainability, and adherence to MathWorks coding standards. Uses checkmatlabcode and matlabcodingguidelines. Use when reviewing code, checking style, finding code smells, assessing quality, or preparing code for handoff or publication.
matlab-analyze-data
matlab/matlab-agentic-toolkit
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.
matlab-design-digital-filter
matlab/matlab-agentic-toolkit
Design and validate digital filters in MATLAB. Use when cleaning up noisy signals, removing interference, filtering signals, designing FIR/IIR filters (lowpass/highpass/bandpass/bandstop/notch), or comparing filters in Filter Analyzer.
matlab-modernize-code
matlab/matlab-agentic-toolkit
Modernize removed or discouraged MATLAB functions and patterns. Use when the checkmatlabcode MCP tool reports that a function "is not recommended", "will be removed in a future release", or "has been removed" — at any severity (info, warning, or error) — when migrating legacy code, or when replacing removed or discouraged APIs with current equivalents. Also applies to discouraged patterns Code Analyzer does not flag (containers.Map, bsxfun, str2num, eval, clear all) and to removed or discouraged functions such as trainNetwork, csvread, xlsread, datenum, guide, svmtrain, ltln2val, webmap.
matlab-create-live-script
matlab/matlab-agentic-toolkit
Create, edit, and run plain-text MATLAB live scripts (.m files) with rich text formatting, LaTeX equations, section breaks, and inline figures. Use when generating tutorials, analysis notebooks, reports, documentation, or educational content, when modifying existing live scripts, or when converting existing binary .mlx files to .m for version control. Requires R2025a+.
matlab-agentic-toolkit-setup
matlab/matlab-agentic-toolkit
Install and configure the MATLAB Agentic Toolkit — detect MATLAB, install the MCP server, register with your AI coding agent, and verify the environment. Supports Claude Code, Codex, GitHub Copilot, Amp, and Gemini CLI.
Popular code quality & workflow skills
grill-me
mattpocock/skills
A relentless interview to sharpen a plan or design.
improve-codebase-architecture
mattpocock/skills
Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
handoff
mattpocock/skills
Compact the current conversation into a handoff document for another agent to pick up.
domain-modeling
mattpocock/skills
Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR.
codebase-design
mattpocock/skills
Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.
diagnosing-bugs
mattpocock/skills
Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.