Skip to main content
ClaudeWave
Skill618 repo starsupdated 8d ago

matlab-optimize-memory

This skill guides users through a systematic 7-step MATLAB memory optimization workflow: establishing a baseline, profiling allocations, identifying bottlenecks, applying optimizations, measuring results, verifying fixes, and documenting changes. Use it when addressing out-of-memory errors, reducing memory consumption, processing larger datasets, or profiling memory allocations in MATLAB code.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-optimize-memory && cp -r /tmp/matlab-optimize-memory/skills-catalog/matlab-software-development/matlab-optimize-memory ~/.claude/skills/matlab-optimize-memory
Then start a new Claude Code session; the skill loads automatically.

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.

```matlab
m0 = memory;
targetFunction(inputs);
m1 = memory;
deltaBytes = m1.MemUsedMATLAB - m0.MemUsedMATLAB;
fprintf('Memory delta: %.2f MB\n', deltaBytes / 1e6);
```

When `memory` is unavailable (Linux/macOS), use `whos` for variable sizes or Java runtime for heap:
```matlab
info = whos('result');
fprintf('Variable size: %.2f MB\n', info.bytes / 1e6);
```

### Step 2: Profile Memory Allocations

Find where memory is being allocated.

```matlab
profile('-memory', 'on');
profile 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
```

**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:

```matlab
m0 = memory;
optimizedFunction(inputs);
m1 = memory;
deltaOpt = m1.MemUsedMATLAB - m0.MemUsedMATLAB;
reduction = 1 - deltaOpt / deltaBaseline;
fprintf('Optimized: %.2f MB (%.0f%% reduction)\n', deltaOpt/1e6, reduction*100);
```

### Step 6: Verify Correctness

Every optimization must produce the same results:

```matlab
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. **Always profile before optimizing** — don't guess where memory is allocated
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` returns an empty struct. Use `whos` for variable sizes, or 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.
matlab-train-networkSkill

>

matlab-driving-data-importerSkill

Import recorded driving sensor data (GPS, camera, lidar, actor tracks, lanes) into scenariobuilder.* objects (GPSData, CameraData, LidarData, ActorTrackData, Trajectory, laneData) and run preprocessing — synchronize, offset correction, crop, normalizeTimestamps, convertTimestamps. Also: compute actor tracks from lidar when no annotations exist, attach camera/lidar mounting + intrinsics, export to MAT/workspace/timetable/script. Use for raw driving dataset files (KITTI, nuScenes, Waymo, Pandaset, ROS/ROS2 bags, .mat, .csv, .mp4) or driving/vehicle/sensor logs that need wrapping. drivingLogAnalyzer (DLA) is OPT-IN ONLY — invoke only on explicit user request ('DLA', 'open in DLA', 'inspect/explore/analyze the recording') or reported sensor problem (sync drift, timestamp mismatch, overlay misalignment). NEVER auto-launch DLA after wrapping (Rule 0). For 'build scenario / export to RoadRunner / drivingScenario / OpenSCENARIO / Unreal / simulate', hand off to matlab-scenario-builder.

matlab-scenario-builderSkill

Generate driving scenes, scenarios, road surfaces, and 3D content from already-wrapped scenariobuilder.* sensor data (GPS, camera, lidar, actor tracks) using Scenario Builder for Automated Driving Toolbox. Use to BUILD, EXPORT, or AUGMENT a virtual scenario/scene/map: ego or actor trajectories, trajectory smoothing, OpenCRG road-surface extraction, 3D asset generation, static-object placement, point-cloud georeferencing + elevation, lane-based ego localization, sensor-fusion tracking, scenario-event extraction (cut-ins, hard brakes, near-misses, ADAS disengagements), or export to RoadRunner, drivingScenario, OpenDRIVE, OpenCRG, OpenSCENARIO, or Unreal Engine. Also: log-to-scenario, scenario harvesting, accident/near-miss reconstruction, SOTIF (ISO 21448) and ISO 26262 scenario coverage, USGS-aerial-lidar scene augmentation, traffic-sign placement from camera+lidar logs. NOT for raw-data import or multi-sensor sync/crop/offset/timestamp normalization — route those to matlab-driving-data-importer.

roadrunner-asset-mappingSkill

>

roadrunner-convert-lanelet2-to-rrhdSkill

>

roadrunner-import-sceneSkill

>

roadrunner-rrhd-authoringSkill

>

matlab-build-simbiology-modelSkill

Build, modify, and diagram SimBiology models — API reference, helper functions, and layout patterns. Use when constructing or editing models programmatically or visually.