matlab-optimize-memory
Guides 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.
- License 许可
- BSD-2-Clause
- 最近更新
- 2026-11-14
- Stars
- ★ 12
- Forks
- 5
01 前言 Front Matter
- name
- matlab-optimize-memory
- license
- MathWorks BSD-3-Clause
- metadata
- { "author": "MathWorks", "version": "1.1" }
- description
- Guides 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.
02 资源文件 3
- 许可证LICENSE.md1.4 KB
- 参考文档manifest.yaml401 B
- 参考文档references/memory-patterns.md1.6 KB
03 SKILL.md 正文
MATLAB Memory Optimization Workflow
Systematic 7-step workflow for finding and fixing memory bottlenecks in MATLAB code.
When to Use
- User gets out-of-memory errors running MATLAB code
- User wants to reduce memory usage of their MATLAB program
- User wants to process larger datasets without running out of memory
- User asks to profile or measure memory allocations
When NOT to Use
- The bottleneck is execution speed, not memory (use
matlab-optimize-performance) - The memory issue is in compiled C/MEX code that can't be changed at the M-code level
- Memory usage is dominated by I/O buffers (memory-mapped files, database connections)
The 7-Step Workflow
Step 1: Establish Memory Baseline
Measure current memory usage before making changes.
m0 = memory;
targetFunction(inputs);
m1 = memory;
deltaBytes = m1.MemUsedMATLAB - m0.MemUsedMATLAB;
fprintf('Memory delta: %.2f MB\n', deltaBytes / 1e6);
When memory errors (Linux/macOS), use whos for variable sizes or Java runtime for heap:
info = whos('result');
fprintf('Variable size: %.2f MB\n', info.bytes / 1e6);
Step 2: Profile Memory Allocations
Find where memory is being allocated.
profile('-memory', 'on');
for iter = 1:5
targetFunction(inputs);
end
profile off;
p = profile('info');
ft = p.FunctionTable;
[~, idx] = sort([ft.TotalMemAllocated], 'descend');
for i = 1:min(15, numel(idx))
f = ft(idx(i));
fprintf('%-40s %10.2f MB\n', f.FunctionName, f.TotalMemAllocated/1e6);
end
If TotalMemAllocated fields are zero, fall back to whos snapshots before/after each function call.
Key things to look for:
- Functions with high "Allocated" but low "Freed" — memory is retained
- Functions called many times with moderate allocations — total adds up
- Large gaps between Allocated and Freed — temporaries accumulating
Step 3: Identify Optimization Opportunities
Based on profiling, identify which patterns apply. See references/memory-patterns.md for code examples.
| Pattern | Typical Reduction | Look For |
|---|---|---|
Cell collection + vertcat |
O(N²) → O(N) | [arr; newRow] inside loops |
Implicit expansion over repmat |
Eliminates full copy | repmat(A, [1 1 K]) for broadcasting |
| Clear variables when done | Immediate reclamation | Large arrays used only in early steps |
| Break chained expressions | 1 fewer peak temporary | a.*b.*c./d all alive at once |
| Reuse variables (overwrite in-place) | Avoids output allocation | Separate variables for each step |
max/min instead of masking |
Eliminates logical temporary | x .* (x > 0) pattern |
zeros(...,'like',x) |
Eliminates temporaries | 0 * x to create zeros |
| Copy-on-write sharing | Shares backing memory | Same array assigned to multiple places |
| Dense → sparse | O(N²) → O(N·bw) | zeros(N,N) where N > 10000 |
Step 4: Implement Optimizations
Apply the identified patterns. Focus only on the hotspots identified in Step 2 — do not apply patterns everywhere.
Step 5: Measure Optimized Memory
Re-measure using the same method as Step 1:
m0 = memory;
optimizedFunction(inputs);
m1 = memory;
deltaOpt = m1.MemUsedMATLAB - m0.MemUsedMATLAB;
reduction = 1 - deltaOpt / deltaBytes;
fprintf('Optimized: %.2f MB (%.0f%% reduction)\n', deltaOpt/1e6, reduction*100);
Step 6: Verify Correctness
Every optimization must produce the same results:
original = originalFunction(inputs);
optimized = optimizedFunction(inputs);
maxErr = max(abs(original(:) - optimized(:)));
fprintf('Max error: %.2e\n', maxErr);
assert(maxErr < 1e-10, 'Results differ!');
Step 7: Report Results
Summarize the memory optimization with baseline, optimized, reduction percentage, correctness check, and patterns applied.
Key Rules
- Never propose optimizations based solely on reading source code — always measure and profile first
- Verify correctness — memory optimizations must produce identical results
- Clear variables early — free memory as soon as data is no longer needed
- Avoid growing arrays — preallocate or use cell collection
- Break chains — sequential assignment reduces peak memory vs chained expressions
- Watch for copies — MATLAB copies on write; reuse variables to avoid duplicates
Platform Notes
- Windows:
memorycommand returns full statistics (MemUsedMATLAB, etc.) - Linux/macOS:
memoryerrors ("not supported on this platform"). Usewhosfor variable sizes, JavaRuntime.getRuntimefor heap usage, or OS-level RSS viasystem('ps ...') profile -memory: Works on all platforms but is undocumented since R2016a. When unavailable, usewhossnapshots before/after function calls.
Copyright 2026 The MathWorks, Inc.
04 同仓库更多 Skills
zarr-python
Stores and queries chunked N-D scientific arrays with Zarr-Python 3, including codecs, sharding, S3/GCS storage, and NumPy/Dask/Xarray integration. Use for array layout, bounded I/O, format migration, or scientific metadata preservation.
yeet
Publish local changes to GitHub by confirming scope, committing intentionally, pushing the branch, and opening a draft PR through the GitHub app from this plugin, with `gh` used only as a fallback where connector coverage is insufficient.
xarray
N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF/GRIB/Zarr files, climate/weather/oceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.
writing-mstest-tests
Use when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for "review" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected/actual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext/lifecycle; timeout/cancellation; OS/CI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest/non-.NET code.
wgs-prs
End-to-end WGS to polygenic risk score pipeline. Takes paired-end FASTQ files (or a pre-existing VCF) through nf-core/sarek for variant calling, applies VCF QC (normalisation, hard filtering, Ti/Tv and Het/Hom checks), then computes polygenic risk scores via the PGS Catalog. Fills the FASTQ to VCF gap upstream of the gwas-prs skill.
webapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.