Profiles and optimizes slow MATLAB code using a 7-step workflow. Measures baseline, profiles with Sampling Profiler (R2026b+) or MATLAB profiler, and reports only measured speedups.
Ships in matlab-software-development. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Systematic 7-step workflow for finding and fixing performance bottlenecks in MATLAB code.
codegen, MEX), or tuning generated MEX (use the matlab-generate-code skill)matlab-optimize-memory skill)matlab-write-performance-tests skill)profile) rather than the Sampling Profiler (Step 2) — that's a profiler choice, not a reason to skip the skillMeasure 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.
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:
nReps, and keep the warm-up call. If it can't be looped, use profile.stacks.TotalSamples/100 is close to its wall clock) and
include no invocation counts. For how many times something ran, use profile, and record
"call_count_source": "builtin_profile_numcalls", "sampling_can_count_invocations": false and
"sampling_profiler_samples" in perf_report.json.Work from the profile to a change:
For the full Sampling Profiler API, results model, traps, and helpers, see references/sampling-profiler.md.
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:
filtfilt/filter instead of looping over columns).Apply the patterns from Step 3, starting with the highest-impact one. Before/after examples are in references/optimization-patterns.md.
discretize, cumsum, hypot) instead of hand-written equivalentsQuick 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:
adjudication_method: "removal_ablation".)100*eps(max(abs(original(:))))), plus an independent witness statistic of the output.median(tb ./ to). Never compare across sessions or in sequential blocks — machine drift lands entirely on one arm.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 and save its results to a .mat as 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.
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.
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.
% column, is the ceiling on what a rewrite can win (this step is ablation)wait(gpuDevice) before and after timing GPU codetimeit — it handles warmup and averaging; avoid raw tic/toc for benchmarksclear what you profiled before you time anything — code run under profile on R2026a stays ~100x slower for the rest of the session until you clear it, so a baseline taken after a profiled run flatters every "after" number. R2026a also has no Sampling Profiler.| 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 |
references/measurement-protocol.md — the verified-result protocol for Step 5 and every perf_report.json fieldreferences/sampling-profiler.md — Sampling Profiler (R2026b+): commands, results model, traps, and the scripts/ helper indexreferences/optimization-patterns.md — the pattern catalog, with before/after code and measured speedupsassets/measurement-templates.md — templates for a timeit baseline, GPU timing, and a scaling testscripts/ — MATLAB helpers for the Sampling Profiler; addpath this folder to use themCopyright 2026 The MathWorks, Inc.
assets/measurement-templates.md (opens in a new tab)manifest.yaml (opens in a new tab)references/measurement-protocol.md (opens in a new tab)references/optimization-patterns.md (opens in a new tab)references/sampling-profiler.md (opens in a new tab)scripts/annotate_source_lines.m (opens in a new tab)scripts/assertSamplingProfiler.m (opens in a new tab)scripts/compare_profiles.m (opens in a new tab)scripts/filter_test_frames.m (opens in a new tab)scripts/find_hotspots.m (opens in a new tab)scripts/make_ab_commands.m (opens in a new tab)scripts/print_hotspot_report.m (opens in a new tab)scripts/profile_function.m (opens in a new tab)scripts/profile_script.m (opens in a new tab)scripts/profile_test.m (opens in a new tab)scripts/quick_profile.m (opens in a new tab)scripts/sampling_profiler.p (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
/matlab-software-development:matlab-optimize-performancefrom matlab-software-development
npx claudepluginhub matlab/matlab-agentic-toolkit --plugin matlab-software-development11 skills in this plugin
/matlab-configure-toml-projectUse whenever "project" or "matlab.toml" is mentioned in a MATLAB context.
This includes creating, editing, organizing, or configuring MATLAB projects,
declaring MATLAB package dependencies or reference projects, setting up paths,
lifecycle scripts, shortcuts, MATLAB packages, or asking about project structure.
/matlab-instrument-opentelemetry-tracingAdd OpenTelemetry tracing to MATLAB code. Use when the user asks to "add tracing", "instrument with spans", "add OpenTelemetry", "trace my code", "add observability" (when about tracing), or mentions "spans", "distributed tracing", or "OTel tracing" in the context of MATLAB functions. Covers span creation, parent-child context propagation, error handling, attributes, events, and semantic conventions.
/matlab-modernize-codeModernize removed or discouraged MATLAB functions and patterns. Use when the check_matlab_code 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-optimize-memoryGuides the 7-step MATLAB memory optimization workflow: baseline, profile, identify, optimize, measure, verify, report. Use when asked to reduce MATLAB memory usage, find memory bottlenecks, fix out-of-memory errors, or optimize memory-intensive code./matlab-package-toolboxTurn raw MATLAB code into a published .mltbx toolbox — full pipeline from scope definition through packaging and release. Drives 8 phases with human checkpoints, enforcing ordering and dependencies. Use when asked to package, create a toolbox, or run the files-to-package pipeline./matlab-run-testsRun MATLAB test suites and analyze results, including test filtering, parallel execution, result diagnostics, code coverage collection, gap analysis, and CI/CD with buildtool. Use when running tests, filtering test suites, analyzing test failures, checking, collecting, or analyzing coverage, justifying uncovered code, or configuring CI pipelines. Do NOT use for writing, generating, or structuring tests. Do NOT use for Simulink coverage or Simulink testing workflows.
Other plugins' skills for the same job