Agent Skillsmatlab/matlab-agentic-toolkit › matlab-optimize-memory

matlab-optimize-memory

GitHub

提供MATLAB内存优化的7步工作流,涵盖基线测量、内存分析、瓶颈识别及代码优化,旨在解决OOM错误和降低内存占用。

skills-catalog/matlab-software-development/matlab-optimize-memory/SKILL.md matlab/matlab-agentic-toolkit

Trigger Scenarios

解决MATLAB运行时的内存溢出错误 需要减少MATLAB程序的内存使用量 希望在不耗尽内存的情况下处理大型数据集 请求对内存分配进行剖析或测量

Install

npx skills add matlab/matlab-agentic-toolkit --skill matlab-optimize-memory -g -y
More Options

Non-standard path

npx skills add https://github.com/matlab/matlab-agentic-toolkit/tree/main/skills-catalog/matlab-software-development/matlab-optimize-memory -g -y

Use without installing

npx skills use matlab/matlab-agentic-toolkit@matlab-optimize-memory

指定 Agent (Claude Code)

npx skills add matlab/matlab-agentic-toolkit --skill matlab-optimize-memory -a claude-code -g -y

安装 repo 全部 skill

npx skills add matlab/matlab-agentic-toolkit --all -g -y

预览 repo 内 skill

npx skills add matlab/matlab-agentic-toolkit --list

SKILL.md

Frontmatter
{
    "name": "matlab-optimize-memory",
    "license": "https:\/\/www.mathworks.com\/content\/dam\/mathworks\/license\/pmrl\/license.md",
    "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."
}

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

  1. Never propose optimizations based solely on reading source code — always measure and profile first
  2. Verify correctness — memory optimizations must produce identical results
  3. Clear variables early — free memory as soon as data is no longer needed
  4. Avoid growing arrays — preallocate or use cell collection
  5. Break chains — sequential assignment reduces peak memory vs chained expressions
  6. Watch for copies — MATLAB copies on write; reuse variables to avoid duplicates

Platform Notes

  • Windows: memory command returns full statistics (MemUsedMATLAB, etc.)
  • Linux/macOS: memory errors ("not supported on this platform"). Use whos for variable sizes, Java Runtime.getRuntime for heap usage, or OS-level RSS via system('ps ...')
  • profile -memory: Works on all platforms but is undocumented since R2016a. When unavailable, use whos snapshots before/after function calls.

Copyright 2026 The MathWorks, Inc.

Version History

  • 2026.08.13 Current 2026-08-16 07:19
  • 2026.07.16 2026-07-24 16:20

Same Skill Collection

skills-catalog/ai-and-statistics/matlab-create-experiment/SKILL.md
skills-catalog/ai-and-statistics/matlab-use-machine-learning-apps/SKILL.md
skills-catalog/automotive/roadrunner-asset-mapping/SKILL.md
skills-catalog/automotive/roadrunner-convert-lanelet2-to-rrhd/SKILL.md
skills-catalog/automotive/roadrunner-core/SKILL.md
skills-catalog/automotive/roadrunner-import-scene/SKILL.md
skills-catalog/automotive/roadrunner-rrhd-authoring/SKILL.md
skills-catalog/automotive/roadrunner-scenario-authoring/SKILL.md
skills-catalog/code-generation/matlab-deploy-embedded-code/SKILL.md
skills-catalog/code-generation/matlab-optimize-gpu-codegen/SKILL.md
skills-catalog/code-generation/matlab-review-fi-code/SKILL.md
skills-catalog/code-generation/matlab-review-fi-object-code/SKILL.md
skills-catalog/computational-biology/matlab-build-simbiology-model/SKILL.md
skills-catalog/computational-biology/matlab-fit-simbiology-model/SKILL.md
skills-catalog/computational-biology/matlab-simulate-simbiology-model/SKILL.md
skills-catalog/computational-finance/matlab-access-datafeed/SKILL.md
skills-catalog/computational-finance/matlab-use-spreadsheet-link/SKILL.md
skills-catalog/control-systems/matlab-extract-battery-features/SKILL.md
skills-catalog/control-systems/matlab-extract-rotating-machinery-features/SKILL.md
skills-catalog/control-systems/matlab-identify-linear-system/SKILL.md
skills-catalog/image-processing-and-computer-vision/matlab-display-image/SKILL.md
skills-catalog/image-processing-and-computer-vision/matlab-display-volume/SKILL.md
skills-catalog/image-processing-and-computer-vision/matlab-model-optics/SKILL.md
skills-catalog/image-processing-and-computer-vision/matlab-point-cloud-file-io/SKILL.md
skills-catalog/image-processing-and-computer-vision/matlab-point-cloud-registration/SKILL.md
skills-catalog/image-processing-and-computer-vision/matlab-process-large-images/SKILL.md
skills-catalog/image-processing-and-computer-vision/matlab-read-write-point-cloud-file/SKILL.md
skills-catalog/image-processing-and-computer-vision/matlab-register-point-clouds/SKILL.md
skills-catalog/math-and-optimization/matlab-solve-optimization/SKILL.md
skills-catalog/matlab-core/matlab-create-live-script/SKILL.md
skills-catalog/matlab-core/matlab-debug-code/SKILL.md
skills-catalog/matlab-core/matlab-debugging/SKILL.md
skills-catalog/matlab-core/matlab-install-products/SKILL.md
skills-catalog/matlab-core/matlab-list-products/SKILL.md
skills-catalog/matlab-core/matlab-read-doc/SKILL.md
skills-catalog/matlab-core/matlab-read-documentation/SKILL.md
skills-catalog/matlab-core/matlab-review-code/SKILL.md
skills-catalog/matlab-core/matlab-testing/SKILL.md
skills-catalog/matlab-core/matlab-write-test/SKILL.md
skills-catalog/matlab-data-import-and-analysis/matlab-analyze-data/SKILL.md
skills-catalog/matlab-data-import-and-analysis/matlab-import-export-data/SKILL.md
skills-catalog/matlab-environment-and-settings/matlab-migrate-settings/SKILL.md
skills-catalog/matlab-external-language-interfaces/matlab-call-python/SKILL.md
skills-catalog/matlab-software-development/matlab-analyze-dependencies/SKILL.md
skills-catalog/matlab-software-development/matlab-assess-toolbox/SKILL.md
skills-catalog/matlab-software-development/matlab-build-toolbox/SKILL.md
skills-catalog/matlab-software-development/matlab-create-buildfile/SKILL.md
skills-catalog/matlab-software-development/matlab-create-project/SKILL.md
skills-catalog/matlab-software-development/matlab-define-toolbox-api/SKILL.md
skills-catalog/matlab-software-development/matlab-document-toolbox/SKILL.md

Metadata

Files
0
Version
2026.08.13
Hash
37e6db16
Indexed
2026-07-24 16:20

inicio - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-16 20:09
浙ICP备14020137号-1 $mapa de visitantes$