Agent Skillsmatlab/matlab-agentic-toolkit › matlab-modernize-code

matlab-modernize-code

GitHub

用于将过时的MATLAB函数和反模式替换为现代等效项,解决代码迁移、API废弃警告及静态分析发现的问题,提升代码安全性与性能。

skills-catalog/matlab-software-development/matlab-modernize-code/SKILL.md matlab/matlab-agentic-toolkit

Trigger Scenarios

check_matlab_code或checkcode报告不推荐或待移除警告 用户请求现代化、迁移或更新旧版MATLAB代码 代码中使用已弃用的API(如csvread, eval等)

Install

npx skills add matlab/matlab-agentic-toolkit --skill matlab-modernize-code -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-modernize-code -g -y

Use without installing

npx skills use matlab/matlab-agentic-toolkit@matlab-modernize-code

指定 Agent (Claude Code)

npx skills add matlab/matlab-agentic-toolkit --skill matlab-modernize-code -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-modernize-code",
    "license": "https:\/\/www.mathworks.com\/content\/dam\/mathworks\/license\/pmrl\/license.md",
    "metadata": {
        "author": "MathWorks",
        "version": "1.2"
    },
    "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.\n"
}

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-debug-code
  • 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

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)

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)

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)

% 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

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

% 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

% 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

% 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
Performance anti-patterns, vectorization, preallocation reference/performance-guidance.md
Signal processing deprecated functions reference/signal-processing-guidance.md
Audio/video I/O migration (wavread, aviread) reference/audio-video-guidance.md
Optimization toolbox (optimset, optimtool) reference/optimization-guidance.md
Control systems plot options reference/control-systems-guidance.md
Image processing ROI objects reference/image-processing-guidance.md
Statistics/ML (svmtrain, dataset, classregtree) reference/statistics-ml-guidance.md
Simulink configuration and blocks reference/simulink-guidance.md
Functions completely removed (guide, optimtool, fints, wavread) reference/removed-functions-guidance.md
Communications System objects reference/communications-guidance.md
Mapping Toolbox (webmap, wmmarker, wmline, geotiffread, mfwdtran, makerefmat) 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.


Version History

  • 2026.08.13 Current 2026-08-16 07:19

    2026.08.13版本发布,更新了部分弃用函数的替代方案及反模式说明。

  • 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
d5d15ed1
Indexed
2026-07-24 16:20

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