Skill Tracer
Skills › Scientific Agent Skills › matlab › programming.md

programming.md

232 lines · skills/matlab/references/programming.md at 5f2bc03

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1# Programming, Projects, Analysis, and Tests
2
3This reference targets MATLAB R2026a. Base MATLAB, separately licensed
4products, and GNU Octave must not be conflated.
5

Programming, Projects, Analysis, and Tests

This reference targets MATLAB R2026a. Base MATLAB, separately licensed products, and GNU Octave must not be conflated.

Raw lines 1 to 5
6## Choose the right code artifact
7
8| Artifact | Workspace | Best use | Main risk |
9|---|---|---|---|
10| script `.m` | caller/base workspace | small reviewed orchestration | hidden inputs, leaked variables, path/state dependence |
11| function `.m` | local workspace | reusable computation and automation | implicit conversions or undocumented side effects |
12| live script `.mlx` | script-like interactive workspace | narrative exploration and teaching | opaque archive, embedded output, weak text review |
13| class `.m` | object state and methods | durable abstractions | constructors, listeners, serialization callbacks |
14| MEX | native process code | approved performance/interface work | arbitrary native execution |
16Prefer a function with explicit inputs, outputs, and an `arguments` block.
17Keep a top-level script thin. Export reviewed live code to plain `.m` before
18static inspection. Never open or run an untrusted project, live script, app,
19class, MEX file, or package.
21Scripts share the base workspace and leave variables there. Functions,
22including local functions, have private workspaces. Since R2024a, local
23functions in scripts can appear anywhere in the file except inside conditional
24contexts. The main function should match its filename.
26```matlab
27function summary = summarizeSignal(signal, options)
28%SUMMARIZESIGNAL Return deterministic summary statistics.
29arguments
30 signal (:,1) double {mustBeFinite}
31 options.Center (1,1) logical = true
32end
34if options.Center
35 signal = signal - mean(signal);
36end
37summary = struct( ...
38 "Count", numel(signal), ...
39 "Mean", mean(signal), ...
40 "StandardDeviation", std(signal));
41end
42```

Choose the right code artifact

ArtifactWorkspaceBest useMain risk
script .mcaller/base workspacesmall reviewed orchestrationhidden inputs, leaked variables, path/state dependence
function .mlocal workspacereusable computation and automationimplicit conversions or undocumented side effects
live script .mlxscript-like interactive workspacenarrative exploration and teachingopaque archive, embedded output, weak text review
class .mobject state and methodsdurable abstractionsconstructors, listeners, serialization callbacks
MEXnative process codeapproved performance/interface workarbitrary native execution

Prefer a function with explicit inputs, outputs, and an arguments block. Keep a top-level script thin. Export reviewed live code to plain .m before static inspection. Never open or run an untrusted project, live script, app, class, MEX file, or package.

Scripts share the base workspace and leave variables there. Functions, including local functions, have private workspaces. Since R2024a, local functions in scripts can appear anywhere in the file except inside conditional contexts. The main function should match its filename.

function summary = summarizeSignal(signal, options)
%SUMMARIZESIGNAL Return deterministic summary statistics.
arguments
    signal (:,1) double {mustBeFinite}
    options.Center (1,1) logical = true
end

if options.Center
    signal = signal - mean(signal);
end
summary = struct( ...
    "Count", numel(signal), ...
    "Mean", mean(signal), ...
    "StandardDeviation", std(signal));
end
Raw lines 6 to 43
44### Argument validation details
46- A size declaration such as `(:,1)` permits a column of any height.
47- Size declarations also reshape compatible vectors or expand scalars. If
48 orientation must be rejected rather than normalized, use a validator such
49 as `mustBeColumn` without a size declaration that reshapes first.
50- A class declaration can convert compatible input. Do not mistake conversion
51 for validation.
52- Validators such as `mustBeFinite` check values without changing them.
53- A default makes an argument optional. Required positional inputs precede
54 optional inputs.
55- Name-value inputs use a structure name in the signature and dotted fields in
56 the block.
57- `namelengthmax` is 2048 from R2025a onward; filesystem limits can be shorter.
58 The bundled static helpers intentionally retain a 63-character subset.
59- Code generation support is a MATLAB Coder capability with additional
60 restrictions and a separate license; an `arguments` block alone does not
61 make code generation available.

Argument validation details

  • A size declaration such as (:,1) permits a column of any height.
  • Size declarations also reshape compatible vectors or expand scalars. If orientation must be rejected rather than normalized, use a validator such as mustBeColumn without a size declaration that reshapes first.
  • A class declaration can convert compatible input. Do not mistake conversion for validation.
  • Validators such as mustBeFinite check values without changing them.
  • A default makes an argument optional. Required positional inputs precede optional inputs.
  • Name-value inputs use a structure name in the signature and dotted fields in the block.
  • namelengthmax is 2048 from R2025a onward; filesystem limits can be shorter. The bundled static helpers intentionally retain a 63-character subset.
  • Code generation support is a MATLAB Coder capability with additional restrictions and a separate license; an arguments block alone does not make code generation available.
Raw lines 44 to 62
63## Workspace and path hygiene
651. Derive files from a confirmed project root, not the user's incidental
66 current folder.
672. Use `fullfile`; never construct paths by concatenating separators.
683. Add the narrowest reviewed directory. Avoid broad `genpath` because it can
69 expose hidden, generated, test, private, or malicious files.
704. Do not silently mutate `path`, `userpath`, preferences, startup files, or
71 Java/native search paths.
725. Avoid `global`, `persistent` cache state without invalidation, and broad
73 clearing. `clear all` can clear loaded functions and disrupt debugging.
746. Use `onCleanup` for resources such as files and temporary state.
757. Pass loaded data through a structure (`S = load(...)`) rather than injecting
76 names into a function or base workspace—but only after the MAT file is
77 trusted.
79MATLAB runs `startup.m` when it is found on the search path and `finish.m` on
80normal exit. Projects can add paths and run startup/shutdown actions. Review all
81of these before execution.

Workspace and path hygiene

  1. Derive files from a confirmed project root, not the user's incidental current folder.
  2. Use fullfile; never construct paths by concatenating separators.
  3. Add the narrowest reviewed directory. Avoid broad genpath because it can expose hidden, generated, test, private, or malicious files.
  4. Do not silently mutate path, userpath, preferences, startup files, or Java/native search paths.
  5. Avoid global, persistent cache state without invalidation, and broad clearing. clear all can clear loaded functions and disrupt debugging.
  6. Use onCleanup for resources such as files and temporary state.
  7. Pass loaded data through a structure (S = load(...)) rather than injecting names into a function or base workspace—but only after the MAT file is trusted.

MATLAB runs startup.m when it is found on the search path and finish.m on normal exit. Projects can add paths and run startup/shutdown actions. Review all of these before execution.

Raw lines 63 to 82
83## Dynamic and external execution surfaces
85Escalate any use of:
87- `eval`, `evalin`, `assignin`, `str2func`, text-derived `feval`, dynamic
88 property or callback names;
89- shell entry points (`system`, `unix`, `dos`, `!`);
90- Java class paths/methods, .NET assemblies, Python (`py.*`, `pyrun`,
91 `pyrunfile`), MEX, C/C++ libraries, and generated code;
92- timers, UI callbacks, listeners, project tasks, build tasks, package startup,
93 and test fixtures with external effects;
94- object loading (`loadobj`, `matlab.mixin.CustomElementSerialization`) and
95 System object load hooks.
97Function handles are safer than text dispatch only when the handle itself comes
98from trusted code. Never pass untrusted text into a dispatch mechanism. Static
99scanning is triage, not proof of absence.

Dynamic and external execution surfaces

Escalate any use of:

  • eval, evalin, assignin, str2func, text-derived feval, dynamic property or callback names;
  • shell entry points (system, unix, dos, !);
  • Java class paths/methods, .NET assemblies, Python (py.*, pyrun, pyrunfile), MEX, C/C++ libraries, and generated code;
  • timers, UI callbacks, listeners, project tasks, build tasks, package startup, and test fixtures with external effects;
  • object loading (loadobj, matlab.mixin.CustomElementSerialization) and System object load hooks.

Function handles are safer than text dispatch only when the handle itself comes from trusted code. Never pass untrusted text into a dispatch mechanism. Static scanning is triage, not proof of absence.

Raw lines 83 to 100
Starts an agent dispatch :97
101## MATLAB Projects
103A project can track files, control the path, declare references and packages,
104run startup/shutdown tasks, integrate source control, and analyze dependencies.
105Use project APIs only after reviewing project metadata and tasks.
107Recommended project record:
109- project name and root;
110- MATLAB release and architecture;
111- entry points and test roots;
112- required and optional MathWorks products, each with license status
113 `unknown`, `confirmed`, or `unavailable`;
114- external system dependencies and generated artifacts;
115- startup/shutdown actions and path changes;
116- RNG/tolerance/data-schema policy.
118Dependency Analyzer and `matlab.codetools.requiredFilesAndProducts` use static
119analysis. Dynamic dispatch, overloaded methods, callbacks, generated names, and
120conditional paths can cause misses or false positives. Their product lists do
121not prove that a license can be checked out.

MATLAB Projects

A project can track files, control the path, declare references and packages, run startup/shutdown tasks, integrate source control, and analyze dependencies. Use project APIs only after reviewing project metadata and tasks.

Recommended project record:

  • project name and root;
  • MATLAB release and architecture;
  • entry points and test roots;
  • required and optional MathWorks products, each with license status unknown, confirmed, or unavailable;
  • external system dependencies and generated artifacts;
  • startup/shutdown actions and path changes;
  • RNG/tolerance/data-schema policy.

Dependency Analyzer and matlab.codetools.requiredFilesAndProducts use static analysis. Dynamic dispatch, overloaded methods, callbacks, generated names, and conditional paths can cause misses or false positives. Their product lists do not prove that a license can be checked out.

Raw lines 101 to 122
Starts an agent dispatch :119
123## Code Analyzer and compatibility checks
125Use these only on trusted text:
127- `codeIssues(path)` returns a structured Code Analyzer result and supports
128 programmatic fixes for eligible issues.
129- `checkcode(path)` remains useful for text-oriented or legacy automation.
130- `codeCompatibilityReport(path)` finds potential issues after a release
131 upgrade.
132- Project Upgrade can check and apply some release migrations and produce a
133 report.
135Do not auto-apply fixes across a scientific codebase without tests. Analyzer
136silence does not establish numerical correctness, security, toolbox
137availability, or Octave compatibility.
139Migration sequence:
1411. Freeze representative outputs and tolerance rationale in the old release.
1422. Record release, products, compilers, BLAS/threading context, RNG algorithm
143 and seed, and external data schema.
1443. Run static compatibility and dependency analysis.
1454. Read every relevant product's release notes and bug reports.
1465. Migrate shared libraries before applications.
1476. Run unit, integration, numerical-equivalence, graphics, and performance
148 checks.
1497. Investigate differences rather than automatically widening tolerances.
151R2026a-specific checks include changed/removed APIs in release notes, new JSON
152table/timetable I/O, Python 3.13 support, string-array Python conversion,
153interactive HTML graphics export, and platform/compiler support. R2026a no
154longer ships new MATLAB releases for Intel Macs.

Code Analyzer and compatibility checks

Use these only on trusted text:

  • codeIssues(path) returns a structured Code Analyzer result and supports programmatic fixes for eligible issues.
  • checkcode(path) remains useful for text-oriented or legacy automation.
  • codeCompatibilityReport(path) finds potential issues after a release upgrade.
  • Project Upgrade can check and apply some release migrations and produce a report.

Do not auto-apply fixes across a scientific codebase without tests. Analyzer silence does not establish numerical correctness, security, toolbox availability, or Octave compatibility.

Migration sequence:

  1. Freeze representative outputs and tolerance rationale in the old release.
  2. Record release, products, compilers, BLAS/threading context, RNG algorithm and seed, and external data schema.
  3. Run static compatibility and dependency analysis.
  4. Read every relevant product's release notes and bug reports.
  5. Migrate shared libraries before applications.
  6. Run unit, integration, numerical-equivalence, graphics, and performance checks.
  7. Investigate differences rather than automatically widening tolerances.

R2026a-specific checks include changed/removed APIs in release notes, new JSON table/timetable I/O, Python 3.13 support, string-array Python conversion, interactive HTML graphics export, and platform/compiler support. R2026a no longer ships new MATLAB releases for Intel Macs.

Raw lines 123 to 155
156## Unit testing
158Base MATLAB includes script-, function-, and class-based `matlab.unittest`
159testing. Keep tests deterministic and independent of order.
161```matlab
162classdef TestSummarizeSignal < matlab.unittest.TestCase
163 methods (Test)
164 function centersFiniteColumn(testCase)
165 actual = summarizeSignal([1; 2; 3]);
166 testCase.verifyEqual(actual.Count, 3);
167 testCase.verifyEqual(actual.Mean, 0, AbsTol=1e-14);
168 end
170 function rejectsNonfiniteInput(testCase)
171 testCase.verifyError( ...
172 @() summarizeSignal([1; NaN]), ...
173 "MATLAB:validators:mustBeFinite");
174 end
175 end
176end
177```
179Use domain-derived `AbsTol` and `RelTol`; exact checks remain appropriate for
180integers, strings, dimensions, and invariants. Isolate file output in temporary
181folders and refuse network, interactive dialogs, or real credentials in unit
182tests.
184Product boundaries:
186- `runtests`, `testsuite`, `matlab.unittest.TestCase`, and ordinary framework
187 plugins are base MATLAB.
188- Parallel test execution requires Parallel Computing Toolbox.
189- Dependency-based test selection, MATLAB Test Manager, Code Quality Dashboard,
190 advanced coverage, generated tests, and equivalence workflows can require
191 MATLAB Test.
192- Requirements traceability can require Requirements Toolbox; generated-code
193 workflows can require MATLAB Coder, MATLAB Compiler SDK, Embedded Coder, or
194 other named products.
196In R2026a, `runtests` automatically opens a project for tests belonging to a
197project that is not already open and closes it afterward. This may execute
198reviewed project startup and shutdown actions; it is not safe for untrusted
199projects.

Unit testing

Base MATLAB includes script-, function-, and class-based matlab.unittest testing. Keep tests deterministic and independent of order.

classdef TestSummarizeSignal < matlab.unittest.TestCase
    methods (Test)
        function centersFiniteColumn(testCase)
            actual = summarizeSignal([1; 2; 3]);
            testCase.verifyEqual(actual.Count, 3);
            testCase.verifyEqual(actual.Mean, 0, AbsTol=1e-14);
        end

        function rejectsNonfiniteInput(testCase)
            testCase.verifyError( ...
                @() summarizeSignal([1; NaN]), ...
                "MATLAB:validators:mustBeFinite");
        end
    end
end

Use domain-derived AbsTol and RelTol; exact checks remain appropriate for integers, strings, dimensions, and invariants. Isolate file output in temporary folders and refuse network, interactive dialogs, or real credentials in unit tests.

Product boundaries:

  • runtests, testsuite, matlab.unittest.TestCase, and ordinary framework plugins are base MATLAB.
  • Parallel test execution requires Parallel Computing Toolbox.
  • Dependency-based test selection, MATLAB Test Manager, Code Quality Dashboard, advanced coverage, generated tests, and equivalence workflows can require MATLAB Test.
  • Requirements traceability can require Requirements Toolbox; generated-code workflows can require MATLAB Coder, MATLAB Compiler SDK, Embedded Coder, or other named products.

In R2026a, runtests automatically opens a project for tests belonging to a project that is not already open and closes it afterward. This may execute reviewed project startup and shutdown actions; it is not safe for untrusted projects.

Raw lines 156 to 200
201## Review checklist
203- [ ] Main function and filename agree.
204- [ ] Inputs, shapes, classes, units, missingness, and outputs are documented.
205- [ ] No hidden base-workspace dependency.
206- [ ] Dynamic/external execution surfaces are absent or explicitly approved.
207- [ ] Paths are project-local and narrow.
208- [ ] Resources close on both success and failure.
209- [ ] Errors have stable identifiers where tests rely on them.
210- [ ] Tests cover edge shapes, empty values, missing values, nonfinite values,
211 numerical tolerances, and failure behavior.
212- [ ] Required products are declared separately from confirmed license status.
213- [ ] Migration evidence includes release notes and representative baselines.

Review checklist

  • [ ] Main function and filename agree.
  • [ ] Inputs, shapes, classes, units, missingness, and outputs are documented.
  • [ ] No hidden base-workspace dependency.
  • [ ] Dynamic/external execution surfaces are absent or explicitly approved.
  • [ ] Paths are project-local and narrow.
  • [ ] Resources close on both success and failure.
  • [ ] Errors have stable identifiers where tests rely on them.
  • [ ] Tests cover edge shapes, empty values, missing values, nonfinite values, numerical tolerances, and failure behavior.
  • [ ] Required products are declared separately from confirmed license status.
  • [ ] Migration evidence includes release notes and representative baselines.
Raw lines 201 to 214
215## Sources (reviewed 2026-10-01)
217- [Scripts vs. Functions](https://www.mathworks.com/help/matlab/matlab_prog/scripts-and-functions.html)
218- [Create Scripts](https://www.mathworks.com/help/matlab/matlab_prog/create-scripts.html)
219- [`arguments`](https://www.mathworks.com/help/matlab/ref/arguments.html)
220- [`mustBeColumn`](https://www.mathworks.com/help/matlab/ref/mustbecolumn.html)
221- [`namelengthmax`](https://www.mathworks.com/help/matlab/ref/namelengthmax.html)
222- [Local Functions](https://www.mathworks.com/help/matlab/matlab_prog/local-functions.html)
223- [MATLAB Projects](https://www.mathworks.com/help/matlab/projects.html)
224- [Analyze Project Dependencies](https://www.mathworks.com/help/matlab/matlab_prog/analyze-project-dependencies.html)
225- [`requiredFilesAndProducts`](https://www.mathworks.com/help/matlab/ref/matlab.codetools.requiredfilesandproducts.html)
226- [MATLAB Code Analyzer Report](https://www.mathworks.com/help/matlab/matlab_prog/matlab-code-analyzer-report.html)
227- [`codeCompatibilityReport`](https://www.mathworks.com/help/matlab/ref/codecompatibilityreport.html)
228- [Project Upgrade](https://www.mathworks.com/help/matlab/matlab_prog/upgrade-projects.html)
229- [Run Unit Tests](https://www.mathworks.com/help/matlab/run-unit-tests.html)
230- [`runtests` R2026a history](https://www.mathworks.com/help/matlab/ref/runtests.html)
231- [MATLAB Test product boundary](https://www.mathworks.com/products/matlab-test.html)
232- [MATLAB release notes](https://www.mathworks.com/help/matlab/release-notes.html)

Sources (reviewed 2026-10-01)

Raw lines 215 to 232