본문으로 건너뛰기
cccskills
무료GitHub에 공개

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.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(3)

  • SKILL.md5.2 KB
  • manifest.yaml450 B
  • references/memory-patterns.md1.6 KB

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.

PatternTypical ReductionLook For
Cell collection + vertcatO(N²) → O(N)[arr; newRow] inside loops
Implicit expansion over repmatEliminates full copyrepmat(A, [1 1 K]) for broadcasting
Clear variables when doneImmediate reclamationLarge arrays used only in early steps
Break chained expressions1 fewer peak temporarya.*b.*c./d all alive at once
Reuse variables (overwrite in-place)Avoids output allocationSeparate variables for each step
max/min instead of maskingEliminates logical temporaryx .* (x > 0) pattern
zeros(...,'like',x)Eliminates temporaries0 * x to create zeros
Copy-on-write sharingShares backing memorySame array assigned to multiple places
Dense → sparseO(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.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Guide for accessing financial and economic data in MATLAB using the Datafeed Toolbox. Covers Bloomberg (market data via bloomberg/blp/bloombergHypermedia), FRED (Federal Reserve economic data via fredrs), Haver Analytics (economic data via haver/haverdirect/haverview), and LSEG Datastream (historical data via datastreamws). Use when connecting to any of these data providers from MATLAB.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

Read BEFORE writing any code that adds Additive White Gaussian Noise (AWGN) to signals and converts between SNR, Eb/No, Es/No, and per-subcarrier SNR for communications simulations, using awgn(), convertSNR(), berawgn(). The default MATLAB patterns for AWGN (e.g., 'measured' option, manual SNR formulas) produce subtly incorrect results. This skill specifies the correct calling conventions, required function usage, and critical anti-patterns that must be avoided.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

Analyze AMS waveform data using Mixed-Signal Blockset utilities: phase noise measurement, clock jitter, anti-aliased resampling, timing measurements, lock time, INL/DNL, ADC/DAC calibration, HSpice import. Use when analyzing time-domain voltage from PLL/VCO/clock simulations, measuring phase noise from variable-step solver output, computing jitter, or resampling non-uniform data.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

Design and analyze electrically large antenna structures using MATLAB Antenna Toolbox. Covers reflector antennas (parabolic, Cassegrain, Gregorian, offset, corner, cylindrical, spherical, custom STL), reflectarrays and reconfigurable intelligent surfaces (RIS), antennas installed on platforms (vehicles, aircraft, ships, satellites), and radar cross section (RCS) analysis. Includes solver selection (MoM-PO, PO, MoM, FMM), mesh control, and GPU acceleration. Use when the user wants to design a dish/reflector antenna, reflectarray, analyze an antenna on a platform, or compute RCS.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

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/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

S-parameters, insertion loss, fields, currents, mesh control, and solver selection for RF PCB performance validation. TRIGGER: user asks to compute S-parameters, analyze insertion/return loss, extract fields or currents, compare MoM vs FEM, or control mesh for any RF PCB component. Invoke BEFORE writing sparameters() or solver code — API is non-obvious. SKIP: designing or creating components (use the specific matlab-design-pcb-* skill), material/stackup setup only (use matlab-manage-pcb-material), optimization sweeps (use matlab-optimize-pcb-design), PDN/IR-drop analysis (use matlab-analyze-pcb-pdn).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

matlab/matlab-agentic-toolkit1.2천2026년 10월 14일 업데이트

matlab의 스킬 모두 보기

이 스킬의 문제 신고