matlab-modernize-code

$npx mdskill add matlab/matlab-agentic-toolkit/matlab-modernize-code

Modernizes deprecated MATLAB functions and patterns to current equivalents.

  • Replaces deprecated functions like csvread, xlsread, and datenum.
  • Depends on check_matlab_code or checkcode for detection.
  • Uses a quick reference table to map deprecated to modern APIs.
  • Outputs updated code with modern equivalents and migration notes.

SKILL.md

.github/skills/matlab-modernize-codeView on GitHub ↗
---
name: matlab-modernize-code
description: >
  Modernize deprecated MATLAB functions and patterns. Use when
  check_matlab_code or checkcode reports "not recommended" or
  "to be removed" warnings, when migrating legacy code, or when
  replacing deprecated APIs (trainNetwork, csvread, xlsread,
  datenum, eval, subplot, guide, optimset, wavread, svmtrain,
  uicontrol) with current equivalents.
license: MathWorks BSD-3-Clause
metadata:
  author: MathWorks
  version: "1.2"
---

# Code Modernization

Replace deprecated MATLAB functions and anti-patterns with modern equivalents. This skill is the resolver — `check_matlab_code` is the detector.

## When to Use

- `check_matlab_code` or `checkcode` returns "not recommended" or "to be removed" warnings
- User asks to modernize, migrate, or update old MATLAB code
- Code uses functions listed in the quick reference table below
- After static analysis reveals deprecated API usage
- Writing new code in a domain that has known deprecated patterns

## When NOT to Use

- Reviewing code quality broadly — use `matlab-review-code` (which may then trigger this skill)
- Debugging runtime errors — use `matlab-debugging`
- Performance profiling — use performance skills (though anti-patterns below overlap)

## Quick Reference: Top Deprecated Functions

| Deprecated | Use instead | Since | Category |
|------------|------------|-------|----------|
| `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` | `datetime` | R2014b | Date/Time |
| `subplot` | `tiledlayout` / `nexttile` | R2019b | Graphics |
| `eval` / `evalc` / `evalin` | Dynamic field names, function handles | — | Security |
| `str2num` | `str2double` | — | Security |
| `trainNetwork` | `trainnet` | R2024a | Deep Learning |
| `LayerGraph` / `SeriesNetwork` | `dlnetwork` | R2024a | Deep Learning |
| `classify` (DL) | `minibatchpredict` + `scores2label` | R2024a | Deep Learning |
| `uicontrol` | `uibutton`, `uidropdown`, etc. | R2016a | UI/App |
| `guide` | `appdesigner` | R2025a | UI (Removed) |
| `optimset` | `optimoptions` | R2013a | Optimization |
| `strmatch` | `startsWith`, `matches` | R2019b | Strings |
| `clear all` | `clearvars` | — | Performance |
| `webmap` | `geoaxes` + `geobasemap` | R2025a | Mapping |

## Critical Anti-Patterns

Never use these in new code:

| Anti-pattern | Problem | Use instead |
|-------------|---------|-------------|
| `eval` / `evalc` / `evalin` | Security risk, prevents JIT optimization, difficult to debug | Dynamic field names `s.(name)`, function handles |
| `str2num` | Uses `eval` internally — code injection risk | `str2double` |
| Growing arrays in loops | O(n²) memory reallocation | Preallocate with `zeros`, `cell` |
| `global` variables | Hidden state, performance penalty | Pass as arguments or use structs |
| `clear all` | Removes functions from memory, forces recompilation | `clearvars` |
| `cd` during execution | Forces function re-resolution | `fullfile` for paths |
| `exist('var','var')` in loops | Expensive state query | Initialize variable before loop |
| Large data in code | Slow parsing, hard to maintain | Save to `.mat` or `.csv` files |

## 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
```

### Vectorization (not loops)
```matlab
% Instead of: for i=1:n, V(i) = pi/12*(D(i)^2)*H(i); end
V = pi/12 * (D.^2) .* H;

% Instead of: loop with if
Vgood = V(D >= 0);   % logical indexing
```

### Preallocation
```matlab
result = zeros(1, n);     % numeric
C = cell(1, n);           % cell array
S(n) = struct('f1', []);  % struct array
```

## 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');
```

### Deep Learning: trainNetwork → trainnet

```matlab
% Old: classificationLayer specifies loss implicitly
net = trainNetwork(X, Y, layers, options);

% Modern: specify loss explicitly, no classificationLayer needed
net = trainnet(X, Y, layers, "crossentropy", options);

% Prediction
scores = minibatchpredict(net, XTest);
YPred = scores2label(scores, classNames);
```

### eval → Dynamic Field Names / Function Handles

```matlab
% Old: eval([varName ' = 42;']);
s.(varName) = 42;

% Old: result = eval(['process_' method '(x)']);
handlers.fast = @processFast;
handlers.slow = @processSlow;
result = handlers.(method)(x);
```

## References

Load these when working in a specific domain:

| Load when... | Reference |
|---|---|
| Deprecated core MATLAB functions (file I/O, strings, deep learning, UI) | [reference/core-functions-guidance.md](reference/core-functions-guidance.md) |
| Performance anti-patterns, vectorization, preallocation | [reference/performance-guidance.md](reference/performance-guidance.md) |
| Signal processing deprecated functions | [reference/signal-processing-guidance.md](reference/signal-processing-guidance.md) |
| Audio/video I/O migration (wavread, aviread) | [reference/audio-video-guidance.md](reference/audio-video-guidance.md) |
| Optimization toolbox (optimset, optimtool) | [reference/optimization-guidance.md](reference/optimization-guidance.md) |
| Control systems plot options | [reference/control-systems-guidance.md](reference/control-systems-guidance.md) |
| Image processing ROI objects | [reference/image-processing-guidance.md](reference/image-processing-guidance.md) |
| Statistics/ML (svmtrain, dataset, classregtree) | [reference/statistics-ml-guidance.md](reference/statistics-ml-guidance.md) |
| Simulink configuration and blocks | [reference/simulink-guidance.md](reference/simulink-guidance.md) |
| Functions completely removed (guide, optimtool, fints, wavread) | [reference/removed-functions-guidance.md](reference/removed-functions-guidance.md) |
| Communications System objects | [reference/communications-guidance.md](reference/communications-guidance.md) |
| Mapping Toolbox (webmap, wmmarker, wmline, geotiffread, mfwdtran, makerefmat) | [reference/mapping-guidance.md](reference/mapping-guidance.md) |

## Conventions

- Always run `check_matlab_code` first — let static analysis find deprecated usage
- **After checkcode, scan the source for patterns checkcode misses:** `subplot` (not flagged), `str2num` (sometimes not flagged), `global` variables, growing arrays may only warn about size change
- Fix deprecated patterns before other code quality issues
- When writing new code, use the modern pattern from the start — don't write deprecated code and fix it later
- For functions marked "Removed" — they will cause immediate errors, not just warnings
- When migrating, test the modern replacement against the old behavior to confirm equivalence
- Consult the domain-specific reference file for detailed migration patterns with code examples

----

Copyright 2026 The MathWorks, Inc.

----

More from matlab/matlab-agentic-toolkit

SkillDescription
matlab-access-datafeed>
matlab-add-awgnRead 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-analyze-ams-waveformAnalyze 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-analyze-dataAnalyze 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, 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-analyze-dependenciesAnalyze the effective toolbox file set to produce a Dependency Manifest — classify all transitive dependencies as included, product, add-on, or external-unresolved, then present resolution options with tradeoffs. Use after matlab-define-toolbox-api when the spec is approved.
matlab-analyze-emS-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-analyze-installed-antennaAnalyze antennas installed on electrically large conducting platforms using MATLAB Antenna Toolbox. Loads platform geometry from STL/STEP/IGES, installs antenna elements, selects electromagnetic solvers (MoM-PO, FMM, MoM), and computes patterns, impedance, coupling, and efficiency. Use when the user wants to model an antenna on a vehicle, aircraft, ship, satellite, or other large structure.
matlab-analyze-pcb-pdnPDN DC voltage/current analysis, IR drop, design rule checking, and multi-net batch analysis on imported PCB layouts. TRIGGER: user asks about power integrity, PDN analysis, IR drop, voltage distribution, current density, power nets, or design rule checking on a PCB. Invoke BEFORE writing code — the PDN API chain is specialized and non-obvious. SKIP: importing a PCB file (use matlab-read-pcb-layout), EM field/S-parameter extraction (use matlab-analyze-em), material/stackup setup only (use matlab-manage-pcb-material), transmission line design (use matlab-design-pcb-txline).
matlab-analyze-rcsCalculate and visualize monostatic and bistatic radar cross section (RCS) using MATLAB Antenna Toolbox. Computes RCS of platforms, antennas, and arrays with PO, MoM, and FMM solvers, supporting HH/VV/HV/VH polarization, GPU acceleration, and near-field observation. Use when the user wants to compute, plot, or analyze radar cross section.
matlab-analyze-rf-propagationAnalyze RF propagation and plan wireless sites using MATLAB Antenna Toolbox. Creates transmitter/receiver sites, computes signal strength, coverage maps, SINR, line-of-sight, and ray tracing in geographic or indoor environments. Supports multiple propagation models (free-space, close-in, Longley-Rice, ray tracing, rain/gas/fog), custom terrain, building data, and directional antennas. Use when the user wants to compute coverage, signal strength, path loss, SINR, ray tracing, or plan a wireless network.