matlab-debug-code
Diagnose MATLAB errors and unexpected behavior. Breakpoints, workspace inspection, try-catch diagnostics, and common error patterns. Use when debugging functions, tracing errors, inspecting variables, or diagnosing runtime failures.
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-debug-code && cp -r /tmp/matlab-debug-code/skills-catalog/matlab-core/matlab-debug-code ~/.claude/skills/matlab-debug-codeSKILL.md
# Investigating and Debugging MATLAB Code with MCP Tools
You have access to a live MATLAB session via MCP tools. Use them to actively
investigate code — whether debugging errors, understanding behavior, or answering
questions about how MATLAB code works. Don't just guess from code alone.
## When to Use
- User encounters a MATLAB error message or unexpected result
- User wants to set breakpoints or inspect variable state
- Tracing why a function produces wrong output
- NaN/Inf values appearing unexpectedly
- A MATLAB MCP tool returns an error or exception — including runtime errors, syntax errors, undefined function/variable errors, or failed test results
- User asks "why is my MATLAB code not working", "help me debug", or shares a MATLAB stack trace
## When NOT to Use
- Code quality review without a runtime problem — use `matlab-reviewing-code` instead
- Performance profiling — use performance optimization workflows
- Writing tests for correctness — use `matlab-write-test` instead
- Understanding MATLAB APIs or language features without a specific bug
## Static Analysis vs Runtime Debugging
Not every issue needs the live MATLAB session. Choose the right approach:
- **Static analysis is enough** when: syntax errors, unused variables, obvious
logic mistakes, or issues visible from reading the source code alone. Use the
`Read` tool and `check_matlab_code`.
- **Runtime debugging is needed** when:
- The error depends on actual data values, types, or dimensions
- The output is wrong but the code looks correct
- The user says "it doesn't work" but the code looks fine — check actual data
- You need to know what variables contain at a specific point in execution
When in doubt, start with static analysis. Escalate to runtime debugging when
you can't determine the root cause from source alone.
## Auto-Trigger on MATLAB Errors
When a MATLAB MCP tool returns an error (runtime error, syntax error, undefined
function/variable, dimension mismatch, failed assertion, etc.), **do not silently
move on or guess at a fix**. Instead:
1. **Recognize the error** — Look for patterns like `Error using ...`,
`Undefined function or variable`, `Index exceeds ...`, `Error in ...`,
MATLAB stack traces, or failed test results in MCP tool output.
2. **Ask the user for permission** — Before launching into investigation, offer:
> "I noticed a MATLAB error: `<brief error summary>`. I can use the
> matlab-debug-code skill to dig into this — inspect variables, trace the
> call stack, and identify the root cause. Want me to investigate?"
3. **Proceed only after confirmation** — Once the user agrees, follow the
investigation workflow below.
This applies whether the error came from the user running code, or from you
running code on the user's behalf (e.g., verifying a fix, running tests).
## Available Tools
| Tool | Use For |
|------|---------|
| `mcp__matlab__run_matlab_file` | **Run .m scripts** — prefer this for executing user scripts and verifying fixes |
| `mcp__matlab__evaluate_matlab_code` | Quick diagnostics: inspect variables, evaluate expressions, test small snippets |
| `mcp__matlab__check_matlab_code` | Static analysis of .m files (warnings, unused vars, potential issues) |
| `mcp__matlab__run_matlab_test_file` | Run a MATLAB test file |
| `mcp__matlab__detect_matlab_toolboxes` | List installed toolboxes — use when "Undefined function" may be a missing toolbox |
**Prefer `run_matlab_file` over `evaluate_matlab_code` for running scripts.** Only
use `evaluate_matlab_code` for short diagnostic commands (checking a variable,
testing an expression, etc.) — not for re-running entire scripts inline.
## Workflow
### 1. Understand the Goal
Determine what the user needs:
- **Debugging** — runtime error, wrong output, unexpected behavior
- **Understanding** — how does this code work, what does this function do
- **Investigating** — why does this variable have this value, where does this data come from
- **Exploring** — what functions are available, how is this codebase structured
### 2. Gather Information via MATLAB
Use `mcp__matlab__evaluate_matlab_code` to run diagnostic commands.
**Read source code:** Use the `Read` tool for .m files on disk — not MATLAB's
`type` or `dbtype`. Only use MATLAB's `which` to locate files you haven't
found yet, and `which -all` to check for shadowing.
**Preview large data:** Use `varName(1:min(5,end),:)` or `head(T)` to preview
slices instead of dumping entire variables.
**Runtime debugging — check desktop mode first:**
Before using breakpoints, check if MATLAB has a desktop:
```matlab
desktop('-inuse') % true = desktop mode, false = no-desktop
```
**Desktop mode (`desktop('-inuse')` returns `true`):**
Use the full breakpoint workflow:
1. **Set a breakpoint before running:**
```matlab
dbstop if error % Pause on any error
dbstop if caught error % Pause on error inside try-catch (silent failures)
dbstop if warning % Pause when a warning is issued
dbstop if naninf % Pause on NaN or Inf
dbstop in file at line % Pause at a specific line
```
2. **Run the code** via `run_matlab_file` — MATLAB pauses at the breakpoint.
3. **Inspect the call stack:**
```matlab
dbstack % See full call stack with file names and line numbers
```
4. **`whos` to see what's in scope** — check variable names, sizes, and types
before inspecting any values. For large arrays/tables, preview a slice
(`varName(1:5,:)`, `head(T)`) instead of displaying the whole thing.
5. **Navigate frames and inspect variables in each scope:**
```matlab
dbup % Move up one frame (toward caller)
dbdown % Move back down (toward callee)
```
After `dbup`/`dbdown`, variable inspection commands operate in that
frame's local scope — use this to check inputs/outputs at each level.
6. **Resume or exit:**
```matlab
dbcont % Continue execution t>
Analyze 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.
Analyze 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.
Analyze 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.
S-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).
Analyze 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.
PDN 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).
Calculate 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.