MATLAB Tutorials

How to Debug MATLAB Code: Breakpoints, Errors and the Workspace

matlab editor
Written by Allie Herry

Every MATLAB user knows the two debugging anti-patterns by heart, because everyone starts with them: staring at the red error message as if it were an insult rather than a diagnosis, and scattering disp and fprintf statements through the code like breadcrumbs, then forgetting to remove half of them. MATLAB actually ships with a proper debugger — breakpoints, a call stack, a live workspace you can interrogate mid-run — and the gap between flailing and debugging is mostly knowing that these tools exist and what order to use them in. This tutorial explains how to debug matlab code methodically: how to read an error message as the information-rich document it is, how breakpoints turn guesswork into inspection, how to isolate a fault with a minimal example, and the habits that prevent the most common bugs from being written at all.

matlab editor

Read the Error Message Like a Diagnosis

An error message is not a verdict; it is the first witness statement, and MATLAB’s are better than their reputation. Read all of it, top to bottom, in order. The final lines name the error and usually the true cause (“Index exceeds the number of array elements”, “Unrecognized function or variable”, “Error using * — Incorrect dimensions for matrix multiplication”); the stack above it is the path the execution took to get there — the chain of function calls, with file names and line numbers, each one clickable in the Editor, taking you to the exact line in the exact function. Most beginners read only the last line and start changing code at the bottom of the stack; the fault is frequently two frames up, where a wrong-shaped array or an empty variable was handed down. Develop the reflex of asking three questions of any error: what line stopped, what were the values at that moment, and what did I assume that the data disagrees with? The third question is the productive one, because most MATLAB errors are assumption errors — the variable you believed was a column vector is a row, the file you believed loaded is empty because its path was wrong, the loop you believed ran ten times ran zero because the range was empty. The error message tells you where reality and your assumptions parted company; debugging is walking back along the stack to find where they first diverged.

Breakpoints: Stop Time and Interrogate the Workspace

The debugger’s core move is the breakpoint: click in the grey margin beside a line (or press F12) and execution pauses there, with the workspace frozen at that instant for inspection. This replaces the entire disp-and-pray methodology. Paused at a breakpoint, you can hover over any variable to see its value, open it in the Variable Editor to inspect a whole array, check sizes with whos, test expressions directly in the Command Window in the paused context — evaluating the failing line’s pieces one at a time to find which operand is wrong — and then step forward line by line (F10), into functions (F11), or out of them (Shift+F11), watching the workspace evolve. Conditional breakpoints elevate the tool from useful to surgical: right-click a breakpoint to set a condition such as i > 97 or any(isnan(x)), and execution pauses only when the condition holds — the technique that finds the loop iteration where the value goes bad on pass 98 of 100, without 97 manual steps. The dbstop if error and dbstop if warning commands automate the reflex: execution halts at the moment of failure with the workspace intact, which matters because the most informative moment in any bug’s life is the instant it happens, with all the evidence still in memory. Learn also the graceful exits — dbquit leaves debug mode, dbclear all removes breakpoints — and the habit of checking the call stack dropdown while paused, because knowing which function called this function, with what arguments, is half of most diagnoses. Our tutorial on speeding up MATLAB code uses the profiler the same way: an instrument first, opinions second.

Isolate: the Minimal Example and the Usual Suspects

When the fault is not an error but a wrong answer — the more dangerous species — isolation is the method. Reduce the problem: copy the suspect function into a fresh script, feed it the smallest input that still produces the wrong result, and shrink from there. A plot that misbehaves on 10,000 points usually misbehaves on five, and five points can be printed, checked by hand and reasoned about. Test functions at their boundaries, because MATLAB bugs breed at the edges: the empty array, the single element, the NaN that propagates silently through a mean (use omitnan consciously, and know that one NaN in a sum makes the sum NaN — by design, and it will find you), the off-by-one at a loop’s first or last index. Keep a mental checklist of the usual suspects, because they account for most wrong answers in practice: row versus column orientation (the apostrophe that transposes, and the .* that should have been * — or the reverse), integer division and type surprises when data arrives as integers from a file, variables silently overwritten because a loop counter reused a name from the workspace (the classic i and j, which are also sqrt(-1) until you overwrite them), functions shadowed by a variable of the same name, and stale results because a script was edited but the section that computes the variable was not rerun — run sections deliberately, and clear the workspace when a result looks impossibly familiar. When truly stuck, explain the code line by line, out loud or in a comment, as if to a colleague: the rubber-duck method works in MATLAB exactly as elsewhere, because the bug lives in the gap between what the code says and what you believe it says, and narration closes that gap.

Prevention: Habits That Write Fewer Bugs

The cheapest debugging is the bug never written, and a few habits pay for themselves immediately. Initialise and preallocate rather than growing variables by accident, and name variables for meaning (sampleRate, not sr, in anything you will reread). Write functions with narrow jobs and check their inputs at the door — a two-line validation (exist checks, size assertions, assert statements that fail loudly with your message) converts mysterious downstream corruption into an immediate, located error. Use the Editor’s built-in Code Analyzer warnings as a free reviewer: the orange underlines flag unreachable code, likely typos, shadowed functions and inefficient patterns while you type, and clearing them is the fastest code review you will ever get. Version your work — even a dated folder of script copies beats the archaeology of final_v3_REAL.m — so that “it worked yesterday” becomes a diff you can inspect rather than a mystery. Save failing inputs as .mat files when you find them; a reproducible failing case is a bug half-fixed and a regression test waiting to be written. And keep a small lab notebook habit: when a bug costs you an hour, write down its cause in one line. The list will embarrass you by repeating itself — orientation, NaNs, stale workspace, shadowing — and that repetition is the point: your personal usual-suspects list, checked first, turns the next debugging session from an afternoon into minutes. Debug with instruments, isolate ruthlessly, and let the code confess.

The Bottom Line

How to debug MATLAB code: read the whole error and walk the stack to where assumptions diverged, pause with breakpoints — conditional ones for loops — and interrogate the workspace at the moment of failure, isolate wrong answers with minimal examples, and prevent repeats with input checks, Code Analyzer warnings and a notebook of your own usual suspects. The debugger is already installed. The method is the upgrade.

About the author

Allie Herry

Leave a Comment