matlab-review-code
matlab-review-code systematically analyzes MATLAB code for quality, correctness, and adherence to MathWorks coding standards using static analysis and manual inspection. Use it when reviewing code for style violations, code smells, and quality issues before handoff or publication, or when users explicitly request code audits or improvements. Do not use it for runtime debugging, performance optimization, or test generation, which require specialized skills instead.
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-review-code && cp -r /tmp/matlab-review-code/skills-catalog/matlab-core/matlab-review-code ~/.claude/skills/matlab-review-codeSKILL.md
# Code Review
Systematically review MATLAB code for quality, correctness, performance, and adherence to MathWorks coding conventions using static analysis and manual inspection patterns.
## When to Use
- User asks to review, audit, or improve code quality
- User wants to check adherence to MathWorks coding standards
- Preparing code for handoff, publication, or open-source release
- After a significant implementation — verify before committing
- User reports "code smells" or asks for cleanup suggestions
## When NOT to Use
- User wants to debug a runtime error — use `matlab-debugging` instead
- User wants to optimize performance — use performance profiling skills
- User wants to generate tests — use `matlab-testing` instead
## Workflow
1. **Run static analysis** — Use `check_matlab_code` MCP tool on all target files
2. **Load coding standards** — Read the `matlab_coding_guidelines` MCP resource
3. **Check naming** — Verify functions, classes, variables, and files follow conventions
4. **Review function signatures** — Arguments blocks, input/output counts, name-value patterns
5. **Assess structure** — Function length, nesting depth, complexity
6. **Check patterns** — Vectorization, preallocation, modern API usage
7. **Summarize** — Report findings by severity: errors > warnings > suggestions
## Step 1: Static Analysis
Use the `check_matlab_code` MCP tool on each file. Then inspect results programmatically:
```matlab
info = checkcode("src/computeArea.m", "-struct");
for k = 1:numel(info)
fprintf('Line %d (col %d-%d): %s\n', ...
info(k).line, info(k).column(1), info(k).column(end), info(k).message);
end
```
For directory-wide analysis (R2022b+):
```matlab
issues = codeIssues("src");
disp(issues.Issues);
```
## Step 2: Load Coding Standards
Read the `matlab_coding_guidelines` MCP resource to get the authoritative MathWorks coding standards. Use these as the baseline for all naming, formatting, and structural checks.
## Review Checklist
### Naming
| Element | Convention | Example |
|---------|-----------|---------|
| Functions | lowerCamelCase, verb phrase | `computeArea`, `loadData` |
| Classes | PascalCase | `SensorReader`, `DataProcessor` |
| Variables | lowerCamelCase, descriptive | `sampleRate` not `sr` |
| Constants | UPPER_SNAKE or `Constant` property | `MAX_ITERATIONS` |
| Test files | `t` prefix | `tComputeArea.m` |
| App files | PascalCase | `DashboardApp.m` |
| File = function | File name matches primary function | `computeArea.m` → `function computeArea` |
### Function Quality
| Check | Standard | Severity |
|-------|----------|----------|
| Input count | Max 6 positional inputs | Warning |
| Output count | Max 4 outputs | Warning |
| Validation | `arguments` block present | Warning |
| Name-value args | `options.Name` pattern (not `varargin`) | Suggestion |
| Length | Flag if >50 lines | Suggestion |
| Nesting | Flag if >3 levels deep | Warning |
| `end` keyword | All functions terminated with `end` | Warning |
| Help text | H1 line present for public functions | Suggestion |
### Code Patterns
| Check | Modern | Legacy (flag it) |
|-------|--------|-------------------|
| Multi-panel figures | `tiledlayout`/`nexttile` | `subplot` |
| Date/time | `datetime` | `datenum`/`datestr` |
| Strings | `string` type | char arrays for text |
| Vectorization | `.*`, `./`, logical indexing | Loops over elements |
| Preallocation | `zeros(n,1)` before loop | Growing arrays in loops |
| Data containers | `table`/`timetable` | Raw matrices for named data |
| Dynamic eval | Direct function calls | `eval`, `evalin`, `assignin` |
### High-Severity Flags
These should always be reported as errors:
- Use of `eval`, `assignin`, or `evalin` — security and maintainability risk
- Growing arrays inside loops without preallocation — performance
- Shadowing built-in functions — `sum = 5` shadows `sum()`
- Missing `arguments` block in public-facing functions
- Hardcoded file paths with backslashes
### What checkcode Misses
`check_matlab_code` does NOT catch all issues. After running static analysis, **always scan the source code** for these common problems that require visual inspection:
- **`subplot` usage** — not flagged by checkcode, but should use `tiledlayout`/`nexttile`
- **Shadowed builtin variables** — `sum = 0` shadows `sum()`, checkcode may not flag it
- **Deep nesting** (>3 levels) — checkcode does not measure nesting depth
- **Hardcoded backslash paths** — checkcode flags unused variables but not path style
- **Magic numbers** — unlabeled constants in code (e.g., `if length(x) > 10`)
- **Missing H1 help text** — checkcode does not require help text
Do not skip Steps 3-6 of the workflow just because checkcode returns few results.
## Patterns
### Complexity Assessment
```matlab
function complexity = assessComplexity(filePath)
%assessComplexity Estimate cyclomatic complexity of a MATLAB function.
arguments
filePath (1,1) string {mustBeFile}
end
code = fileread(filePath);
branchKeywords = ["if " "elseif " "case " "while " "for " "catch "];
complexity = 1;
for kw = branchKeywords
complexity = complexity + numel(strfind(code, kw));
end
end
```
### Check Toolbox Dependencies
```matlab
[files, products] = matlab.codetools.requiredFilesAndProducts('src/myFunction.m');
fprintf('Required products:\n');
for k = 1:numel(products)
fprintf(' %s (ID: %d)\n', products(k).Name, products(k).ProductNumber);
end
```
### Review Report Format
Present findings in this format:
```
## Code Review: computeArea.m
### Static Analysis (checkcode)
- 2 warnings, 0 errors
### Naming ✓
- [x] Function: lowerCamelCase
- [x] Variables: descriptive
- [x] File name matches function
### Structure
- [x] arguments block present
- [x] Function under 50 lines
- [ ] ⚠ Nesting depth reaches 4 levels (line 32)
### Patterns
- [x] Vectorized
- [x] Modern graphics API
- [ ] ⚠ Uses datenum (line 18) — migrate to datetime
### Suggestions
1. Extract>
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.
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.
>
>
>
>
Build, modify, and diagram SimBiology models — API reference, helper functions, and layout patterns. Use when constructing or editing models programmatically or visually.