Skip to main content
ClaudeWave
Skill1k repo starsupdated yesterday

matlab-modernize-code

This skill modernizes MATLAB code by replacing deprecated functions and anti-patterns with current equivalents. Use it when static analysis tools like `checkcode` flag "not recommended" or "to be removed" warnings, or when migrating legacy code that uses outdated APIs such as `csvread`, `subplot`, `eval`, or `datenum`. It serves as the automated resolver paired with the `check_matlab_code` detector skill.

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

SKILL.md

# Code Modernization

Replace removed or discouraged MATLAB functions and anti-patterns with modern equivalents. This skill is the resolver — the MCP tool `check_matlab_code` (MATLAB's Code Analyzer) is the detector.

**Terms used in this skill:**
- **Removed** — the function is no longer in MATLAB; calling it errors.
- **Discouraged** — the function still works, but a better API exists. It may or may not be slated for removal in a future release.

## When to Use

- `check_matlab_code` reports a lifecycle diagnostic — any of these three
  wordings, matched case-insensitively (`STRMATCH is not recommended` is the
  same signal as the lowercase form):
  - `'X' is not recommended...` (severity: info)
  - `'X' will be removed in a future release...` (severity: warning)
  - `'X' has been removed...` (severity: error — the code errors today)
- Code uses a discouraged pattern Code Analyzer does *not* flag — e.g. `containers.Map`, `bsxfun`, `str2num`, `eval`, `clear all` — scan the source, not just the diagnostics (see Conventions)
- User asks to modernize, migrate, or update old MATLAB code
- Code uses functions listed in the quick reference table below
- After static analysis reveals removed or discouraged API usage
- Writing new code in a domain that has known removed or discouraged patterns

## When NOT to Use

This skill swaps removed or discouraged APIs for modern equivalents. It does not:

- Review code quality broadly
- Debug runtime behavior (removed-function errors excepted — those are modernization fixes)
- Optimize already-correct code for speed → hand off to `matlab-optimize-performance`
- Write or migrate function input/output validation (`arguments` blocks, `inputParser`/`validateattributes` → `mustBe*` validators, repeating args, name-value forwarding) → hand off to `matlab-validate-function-arguments`

## Quick Reference: Removed, Discouraged & Anti-Patterns

| Topic | Recommendation | Since | Category | Rationale |
|---|---|---|---|---|
| `csvread` / `dlmread` | `readmatrix` | R2019a | File I/O | |
| `csvwrite` / `dlmwrite` | `writematrix` | R2019a | File I/O | |
| `xlsread` | `readtable`, `readmatrix` | R2019a | File I/O | |
| `xlswrite` | `writetable`, `writematrix` | R2019a | File I/O | |
| `datenum` / `datestr` / `now` | `datetime` (use `string`/`char` to format) | R2022b | Date/Time (Not recommended) | Flagged by Code Analyzer |
| `eval` / `evalc` / `evalin` | Dynamic field names `s.(name)`, function handles / `feval`, cells for sequential names | — | Anti-pattern | Not compiled (slow); can overwrite workspace vars; hard to debug; injection risk |
| `str2num` | `str2num(text, Evaluation="restricted")` | R2022a | Security | Unrestricted form runs input via `eval` (injection risk); see references |
| `uicontrol` | `uibutton`, `uidropdown`, etc. | R2016a | UI/App | |
| `guide` | `appdesigner` | R2025a | UI (Removed) | |
| `strmatch` | `startsWith`, `matches` | R2019b | Strings | |
| `clear all` | `clearvars` | — | Workspace | Clears functions from memory; forces recompilation |

> **`datestr` nuance:** `datestr`'s job was to format a date as *text*, so its modern replacement is
> `string(dt)` / `char(dt)` or setting `dt.Format` — not a bare `datetime(...)` call. Use `datetime`
> to replace `datenum`/`now` (the numeric/serial-date path). Neither is removed; both are Code
> Analyzer "not recommended" as of R2022b.
>
> ```matlab
> s = datestr(t, 'yyyy-mm-dd HH:MM:SS');          % old
> s = string(t, 'yyyy-MM-dd HH:mm:ss');           % new — note the specifiers change:
>                                                 % datetime uses MM=month, mm=minute (datestr had mm=month, MM=minute)
> ```

## Modern Design Patterns

Prefer these in all new code:

### Table-Based Workflows
```matlab
data = readtable('sensors.csv');
data.Timestamp = datetime(data.Timestamp);
data.Status = categorical(data.Status);
recentData = data(data.Timestamp > datetime('today') - days(7), :);
summary = groupsummary(recentData, 'SensorID', 'mean', 'Value');
```

### String Arrays (not char arrays)
```matlab
name = "John";                        % not 'John'
names = ["John", "Jane", "Bob"];      % not {'John','Jane','Bob'}
fullName = firstName + " " + lastName; % not [first,' ',last]
idx = contains(names, "Jo");          % not cellfun + strfind
```

### Arguments Block (not nargin/varargin)
```matlab
function result = processData(data, options)
    arguments
        data (:,:) double
        options.Method (1,1) string {mustBeMember(options.Method, ["fast","accurate"])} = "fast"
        options.Verbose (1,1) logical = false
    end
end
```

## Key Migrations

### File I/O: csvread/xlsread → readmatrix/readtable

```matlab
% Old                          → Modern
M = csvread('data.csv');       % M = readmatrix("data.csv");
M = dlmread('data.txt','\t'); % M = readmatrix("data.txt", Delimiter="\t");
[n,t,r] = xlsread('f.xlsx');  % T = readtable("f.xlsx");
csvwrite('out.csv', M);       % writematrix(M, "out.csv");
xlswrite('out.xlsx', data);   % writetable(T, "out.xlsx");
```

### eval → Structured Alternatives

Avoid `eval`/`evalc`/`evalin`: the text isn't compiled (slower), can silently overwrite workspace
variables, and is hard to read/debug. Match the intent to a construct — see
`references/core-functions-guidance.md` for the full set (sequential names, `sprintf` filenames,
`try/catch`).

```matlab
% Old: eval([varName ' = 42;']);          -> dynamic field name
s.(varName) = 42;

% Old: result = eval(['process_' method '(x)']);  -> handle dispatch table
handlers.fast = @processFast;
handlers.slow = @processSlow;
result = handlers.(method)(x);

% Old: for n=1:10, eval(['A' int2str(n) '=magic(n);']); end  -> index a cell
A = cell(10,1);
for n = 1:10, A{n} = magic(n); end
```

## References

Load these when working in a specific domain:

| Load when... | Reference |
|---|---|
| Core MATLAB functions (file I/O, strings, UI); security anti-patterns (`eval`/`str2num`), `containers.Map`→`dictionary`, `bsxfun`→impli
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.