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-review-code instead
- Performance profiling — use performance optimization workflows
- Writing tests for correctness — use
matlab-write-tests 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:
- 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.
- 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?"
- 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:
desktop('-inuse') % true = desktop mode, false = no-desktop
Desktop mode (desktop('-inuse') returns true):
Use the full breakpoint workflow:
- Set a breakpoint before running:
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
- Run the code via
run_matlab_file — MATLAB pauses at the breakpoint.
- Inspect the call stack:
dbstack % See full call stack with file names and line numbers
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.
- Navigate frames and inspect variables in each scope:
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.
- Resume or exit:
dbcont % Continue execution to next breakpoint or end
dbquit % Exit debug mode entirely
dbclear all % Remove all breakpoints when done
Note: Interactive stepping (dbstep) is unreliable via MCP — each
evaluate_matlab_code call is a separate command, so step state may not
persist.
No-desktop mode (desktop('-inuse') returns false):
Do NOT use dbstop if error, dbstop if naninf, dbstop if warning, or
any breakpoint that pauses execution. In no-desktop mode, pausing breakpoints
cause the MCP eval to hang indefinitely.
Use these strategies instead:
try-catch wrappers — Wrap suspect code to capture the error and
inspect state after failure:
try
result = suspectFunction(data);
catch ME
fprintf('Error: %s\n', ME.message);
fprintf('In: %s line %d\n', ME.stack(1).name, ME.stack(1).line);
whos % Show variables in scope at failure
end
Tracer conditional breakpoints — Use dbstop with a condition
that always returns false so MATLAB never actually pauses, but prints
the value as a side effect. Define a tracer function:
function out = tracer(val)
disp(val);
out = false;
end
Then set a conditional breakpoint that calls it:
dbstop in myScript at 42 if tracer(myVar)
When line 42 executes, MATLAB evaluates tracer(myVar), which prints
the value and returns false — execution continues without pausing.
This probes variables at specific lines without modifying the source file.
Remove tracer breakpoints when done: dbclear all
Run then inspect — For scripts, run via run_matlab_file, then use
evaluate_matlab_code to inspect workspace variables after execution.
The base workspace persists across MCP calls within a session.
3. Investigate Iteratively
This is the core of debugging — use your judgment:
- Read the relevant source code to understand intent
- Inspect variables that appear on or near the failing line
- Evaluate sub-expressions to isolate which part fails
- Test hypotheses by running small snippets in MATLAB
- Be selective — don't dump the entire workspace. Only inspect what is relevant
to the problem. If there are 7 variables in scope but only 2 are used on the
failing line, inspect those 2.
When the error occurs inside a MathWorks built-in function, the bug is almost
always in the user's code that called it. Walk up the stack to user code.
4. Question the Diagnosis
The user's description of the problem may not match the actual problem. Before
fixing what they say is broken, verify it yourself:
- Test the claimed failure directly — If the user says
ismember or strcmp
doesn't work, run it yourself with their actual data. Often the operation works
fine and the real issue is the logic around it.
- Check data before blaming code — When operations on data "don't work,"
inspect the data: types (
class), actual values (sample a few), whitespace
(strtrim), hidden characters (double(str)), and dimensions (size).
- Verify what the code does vs what the user describes — Read the code and
confirm which variables and columns are actually being used. The user may
describe their intent but the code may do something different.
- Consider whether the approach itself is wrong — Sometimes the code has no
bug per se, but the approach is unnecessarily complex or fragile. Suggest
idiomatic MATLAB alternatives: table joins instead of manual loops, vectorized
operations instead of element-wise comparisons, built-in functions instead of
hand-rolled logic.
Common Errors — What to Check First
| Error Pattern |
Diagnostic Steps |
Undefined function or variable 'X' |
which X, exist('X','file'), exist('X','var'), check path, use detect_matlab_toolboxes to verify toolbox is installed |
Index exceeds array dimensions / Index exceeds the number of array elements |
size(arr) and inspect the index expression — often off-by-one or empty array |
Not enough input arguments |
Check how the function is called at the call site, nargin inside the function, compare with function signature |
Too many input arguments |
Same as above — caller passing extra args, or calling a script as if it were a function |
Matrix dimensions must agree / Dimension mismatch |
size(A), size(B) for both operands — often one is row and the other column |
Subscript indices must either be real positive integers or logicals |
Check index variable: class(idx), min(idx), look for 0 or negative values, NaN, or floating-point indices |
Dot indexing is not supported for variables of this type |
class(var) — usually accessing a struct field on a non-struct (cell, array, table) |
Unable to perform assignment |
Check class and size of both sides of the assignment |
Out of memory |
whos to find large variables, check for accidental array growth in loops |
Maximum recursion limit |
Check for missing base case or infinite mutual recursion — dbstack at error point |
| NaN propagation / wrong branch taken |
In desktop mode, use dbstop if naninf to catch where NaN is first created. In no-desktop mode, use dbstop in file at line if tracer(suspect) to probe values without pausing. NaN comparisons (>, <, ==) are always false, so if takes the wrong branch silently. Trace upstream: check for 0/0, Inf-Inf, or NaN in input data. Use any(isnan(var)) to test. |
Gotchas
Key Principles
- Use the tools — You have a live MATLAB session. Run commands, inspect
state, test hypotheses. Don't debug from code reading alone.
- Be selective — Request only what's relevant. Don't dump all variables or
read every file in the stack.
- Check size before fetching data — Always know the dimensions before
displaying a variable. Never blindly
disp an unknown variable.
- Focus on user code — Errors surfacing in built-in functions are almost
always caused by bad inputs from user code.
- Read before fixing — Always read the actual source code before suggesting
changes. Never guess what code looks like.
- Verify fixes — When practical, run the corrected code in MATLAB to confirm.
Copyright 2026 The MathWorks, Inc.
1---2name: matlab-debug-code3description: 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.4license: https://www.mathworks.com/content/dam/mathworks/license/pmrl/license.md5metadata:6 source: https://skillmd.com/skills/matlab/matlab-debug-code7 author: MathWorks8 version: "3.1"9---1011# Investigating and Debugging MATLAB Code with MCP Tools1213You have access to a live MATLAB session via MCP tools. Use them to actively14investigate code — whether debugging errors, understanding behavior, or answering15questions about how MATLAB code works. Don't just guess from code alone.1617## When to Use1819- User encounters a MATLAB error message or unexpected result20- User wants to set breakpoints or inspect variable state21- Tracing why a function produces wrong output22- NaN/Inf values appearing unexpectedly23- A MATLAB MCP tool returns an error or exception — including runtime errors, syntax errors, undefined function/variable errors, or failed test results24- User asks "why is my MATLAB code not working", "help me debug", or shares a MATLAB stack trace2526## When NOT to Use2728- Code quality review without a runtime problem — use `matlab-review-code` instead29- Performance profiling — use performance optimization workflows30- Writing tests for correctness — use `matlab-write-tests` instead31- Understanding MATLAB APIs or language features without a specific bug3233## Static Analysis vs Runtime Debugging3435Not every issue needs the live MATLAB session. Choose the right approach:3637- **Static analysis is enough** when: syntax errors, unused variables, obvious38 logic mistakes, or issues visible from reading the source code alone. Use the39 `Read` tool and `check_matlab_code`.40- **Runtime debugging is needed** when:41 - The error depends on actual data values, types, or dimensions42 - The output is wrong but the code looks correct43 - The user says "it doesn't work" but the code looks fine — check actual data44 - You need to know what variables contain at a specific point in execution4546When in doubt, start with static analysis. Escalate to runtime debugging when47you can't determine the root cause from source alone.4849## Auto-Trigger on MATLAB Errors5051When a MATLAB MCP tool returns an error (runtime error, syntax error, undefined52function/variable, dimension mismatch, failed assertion, etc.), **do not silently53move on or guess at a fix**. Instead:54551. **Recognize the error** — Look for patterns like `Error using ...`,56 `Undefined function or variable`, `Index exceeds ...`, `Error in ...`,57 MATLAB stack traces, or failed test results in MCP tool output.582. **Ask the user for permission** — Before launching into investigation, offer:59 > "I noticed a MATLAB error: `<brief error summary>`. I can use the60 > matlab-debug-code skill to dig into this — inspect variables, trace the61 > call stack, and identify the root cause. Want me to investigate?"623. **Proceed only after confirmation** — Once the user agrees, follow the63 investigation workflow below.6465This applies whether the error came from the user running code, or from you66running code on the user's behalf (e.g., verifying a fix, running tests).6768## Available Tools6970| Tool | Use For |71|------|---------|72| `mcp__matlab__run_matlab_file` | **Run .m scripts** — prefer this for executing user scripts and verifying fixes |73| `mcp__matlab__evaluate_matlab_code` | Quick diagnostics: inspect variables, evaluate expressions, test small snippets |74| `mcp__matlab__check_matlab_code` | Static analysis of .m files (warnings, unused vars, potential issues) |75| `mcp__matlab__run_matlab_test_file` | Run a MATLAB test file |76| `mcp__matlab__detect_matlab_toolboxes` | List installed toolboxes — use when "Undefined function" may be a missing toolbox |7778**Prefer `run_matlab_file` over `evaluate_matlab_code` for running scripts.** Only79use `evaluate_matlab_code` for short diagnostic commands (checking a variable,80testing an expression, etc.) — not for re-running entire scripts inline.8182## Workflow8384### 1. Understand the Goal8586Determine what the user needs:87- **Debugging** — runtime error, wrong output, unexpected behavior88- **Understanding** — how does this code work, what does this function do89- **Investigating** — why does this variable have this value, where does this data come from90- **Exploring** — what functions are available, how is this codebase structured9192### 2. Gather Information via MATLAB9394Use `mcp__matlab__evaluate_matlab_code` to run diagnostic commands.9596**Read source code:** Use the `Read` tool for .m files on disk — not MATLAB's97`type` or `dbtype`. Only use MATLAB's `which` to locate files you haven't98found yet, and `which -all` to check for shadowing.99100**Preview large data:** Use `varName(1:min(5,end),:)` or `head(T)` to preview101slices instead of dumping entire variables.102103**Runtime debugging — check desktop mode first:**104105Before using breakpoints, check if MATLAB has a desktop:106```matlab107desktop('-inuse') % true = desktop mode, false = no-desktop108```109110**Desktop mode (`desktop('-inuse')` returns `true`):**111112Use the full breakpoint workflow:1131141. **Set a breakpoint before running:**115 ```matlab116 dbstop if error % Pause on any error117 dbstop if caught error % Pause on error inside try-catch (silent failures)118 dbstop if warning % Pause when a warning is issued119 dbstop if naninf % Pause on NaN or Inf120 dbstop in file at line % Pause at a specific line121 ```1222. **Run the code** via `run_matlab_file` — MATLAB pauses at the breakpoint.1233. **Inspect the call stack:**124 ```matlab125 dbstack % See full call stack with file names and line numbers126 ```1274. **`whos` to see what's in scope** — check variable names, sizes, and types128 before inspecting any values. For large arrays/tables, preview a slice129 (`varName(1:5,:)`, `head(T)`) instead of displaying the whole thing.1305. **Navigate frames and inspect variables in each scope:**131 ```matlab132 dbup % Move up one frame (toward caller)133 dbdown % Move back down (toward callee)134 ```135 After `dbup`/`dbdown`, variable inspection commands operate in that136 frame's local scope — use this to check inputs/outputs at each level.1376. **Resume or exit:**138 ```matlab139 dbcont % Continue execution to next breakpoint or end140 dbquit % Exit debug mode entirely141 dbclear all % Remove all breakpoints when done142 ```143144**Note:** Interactive stepping (`dbstep`) is unreliable via MCP — each145`evaluate_matlab_code` call is a separate command, so step state may not146persist.147148**No-desktop mode (`desktop('-inuse')` returns `false`):**149150**Do NOT use `dbstop if error`, `dbstop if naninf`, `dbstop if warning`, or151any breakpoint that pauses execution.** In no-desktop mode, pausing breakpoints152cause the MCP eval to hang indefinitely.153154Use these strategies instead:1551561. **try-catch wrappers** — Wrap suspect code to capture the error and157 inspect state after failure:158 ```matlab159 try160 result = suspectFunction(data);161 catch ME162 fprintf('Error: %s\n', ME.message);163 fprintf('In: %s line %d\n', ME.stack(1).name, ME.stack(1).line);164 whos % Show variables in scope at failure165 end166 ```1671682. **Tracer conditional breakpoints** — Use `dbstop` with a condition169 that always returns `false` so MATLAB never actually pauses, but prints170 the value as a side effect. Define a tracer function:171 ```matlab172 function out = tracer(val)173 disp(val);174 out = false;175 end176 ```177 Then set a conditional breakpoint that calls it:178 ```matlab179 dbstop in myScript at 42 if tracer(myVar)180 ```181 When line 42 executes, MATLAB evaluates `tracer(myVar)`, which prints182 the value and returns `false` — execution continues without pausing.183 This probes variables at specific lines without modifying the source file.184 Remove tracer breakpoints when done: `dbclear all`1851863. **Run then inspect** — For scripts, run via `run_matlab_file`, then use187 `evaluate_matlab_code` to inspect workspace variables after execution.188 The base workspace persists across MCP calls within a session.189190### 3. Investigate Iteratively191192This is the core of debugging — use your judgment:193194- **Read the relevant source code** to understand intent195- **Inspect variables** that appear on or near the failing line196- **Evaluate sub-expressions** to isolate which part fails197- **Test hypotheses** by running small snippets in MATLAB198- **Be selective** — don't dump the entire workspace. Only inspect what is relevant199 to the problem. If there are 7 variables in scope but only 2 are used on the200 failing line, inspect those 2.201202When the error occurs inside a MathWorks built-in function, the bug is almost203always in the **user's code that called it**. Walk up the stack to user code.204205### 4. Question the Diagnosis206207The user's description of the problem may not match the actual problem. Before208fixing what they say is broken, verify it yourself:209210- **Test the claimed failure directly** — If the user says `ismember` or `strcmp`211 doesn't work, run it yourself with their actual data. Often the operation works212 fine and the real issue is the logic around it.213- **Check data before blaming code** — When operations on data "don't work,"214 inspect the data: types (`class`), actual values (sample a few), whitespace215 (`strtrim`), hidden characters (`double(str)`), and dimensions (`size`).216- **Verify what the code does vs what the user describes** — Read the code and217 confirm which variables and columns are actually being used. The user may218 describe their intent but the code may do something different.219- **Consider whether the approach itself is wrong** — Sometimes the code has no220 bug per se, but the approach is unnecessarily complex or fragile. Suggest221 idiomatic MATLAB alternatives: table joins instead of manual loops, vectorized222 operations instead of element-wise comparisons, built-in functions instead of223 hand-rolled logic.224225226## Common Errors — What to Check First227228| Error Pattern | Diagnostic Steps |229|---------------|-----------------|230| `Undefined function or variable 'X'` | `which X`, `exist('X','file')`, `exist('X','var')`, check `path`, use `detect_matlab_toolboxes` to verify toolbox is installed |231| `Index exceeds array dimensions` / `Index exceeds the number of array elements` | `size(arr)` and inspect the index expression — often off-by-one or empty array |232| `Not enough input arguments` | Check how the function is called at the call site, `nargin` inside the function, compare with function signature |233| `Too many input arguments` | Same as above — caller passing extra args, or calling a script as if it were a function |234| `Matrix dimensions must agree` / `Dimension mismatch` | `size(A)`, `size(B)` for both operands — often one is row and the other column |235| `Subscript indices must either be real positive integers or logicals` | Check index variable: `class(idx)`, `min(idx)`, look for 0 or negative values, NaN, or floating-point indices |236| `Dot indexing is not supported for variables of this type` | `class(var)` — usually accessing a struct field on a non-struct (cell, array, table) |237| `Unable to perform assignment` | Check `class` and `size` of both sides of the assignment |238| `Out of memory` | `whos` to find large variables, check for accidental array growth in loops |239| `Maximum recursion limit` | Check for missing base case or infinite mutual recursion — `dbstack` at error point |240| NaN propagation / wrong branch taken | In desktop mode, use `dbstop if naninf` to catch where NaN is first created. In no-desktop mode, use `dbstop in file at line if tracer(suspect)` to probe values without pausing. NaN comparisons (`>`, `<`, `==`) are always `false`, so `if` takes the wrong branch silently. Trace upstream: check for `0/0`, `Inf-Inf`, or NaN in input data. Use `any(isnan(var))` to test. |241242## Gotchas243244- **Pausing breakpoints hang in no-desktop mode.** When `desktop('-inuse')`245 returns `false`, `dbstop if error`, `dbstop if naninf`, `dbstop if warning`,246 and unconditional line breakpoints cause MCP eval to hang indefinitely. Always247 check desktop mode first. In no-desktop mode, use tracer conditional248 breakpoints or try-catch wrappers instead (see no-desktop strategies above).249- **`dbstep` does not work reliably via MCP.** Each `evaluate_matlab_code` call250 is a separate command, so step state may not persist between calls. Use251 breakpoints (`dbstop in file at line`) to pause at specific locations instead252 of trying to step through code. For tracing execution flow, insert temporary253 `fprintf()` statements or use try-catch blocks.254- **Do not use `type` or `dbtype` to read source code.** Use the `Read` tool255 instead — it's faster and doesn't consume MATLAB session output bandwidth.256 Only use `which` to locate files you haven't found yet.257- **Always `dbclear all` when done debugging.** Leftover breakpoints from a258 previous session will cause unexpected pauses in later runs.259- **`dbup`/`dbdown` scope is per-call.** Each `evaluate_matlab_code` invocation260 resets to the current frame. Chain `dbup` with variable inspection in the261 same `evaluate_matlab_code` call:262 ```matlab263 dbup; whos; myVar(1:min(5,end),:)264 ```265 A separate `evaluate_matlab_code` call after `dbup` will be back in the266 original frame.267- **Never run `restoredefaultpath`.** It removes the MCP server's own packages268 from the MATLAB path, breaking the eval channel (`mcpEval` not found). If this269 happens, the only recovery is to restart MATLAB entirely.270- **No toolboxes required.** This skill uses only base MATLAB debugging commands.271272## Key Principles273274- **Use the tools** — You have a live MATLAB session. Run commands, inspect275 state, test hypotheses. Don't debug from code reading alone.276- **Be selective** — Request only what's relevant. Don't dump all variables or277 read every file in the stack.278- **Check size before fetching data** — Always know the dimensions before279 displaying a variable. Never blindly `disp` an unknown variable.280- **Focus on user code** — Errors surfacing in built-in functions are almost281 always caused by bad inputs from user code.282- **Read before fixing** — Always read the actual source code before suggesting283 changes. Never guess what code looks like.284- **Verify fixes** — When practical, run the corrected code in MATLAB to confirm.285286----287288Copyright 2026 The MathWorks, Inc.289290----