Debugging in MATLAB
Debugging means finding and fixing errors (bugs) in your MATLAB program. MATLAB
provides tools to help you pause the execution of a program, inspect variable values, and
make corrections.
Example M-file
Let’s take an example M-file named sum_of_squares.m:
function total = sum_of_squares(n)
total = 0;
for i = 1:n
total = total + i^2;
end
end
Now suppose we accidentally made a mistake like this:
function total = sum_of_squares(n)
total = 0;
for i = 1:n
total = total + i*2; % Wrong: should be i^2
end
end
We’ll use the debugging process to find and fix this bug.
Steps in the Debugging Process
1. Preparing for Debugging
Before debugging, ensure your M-file is saved without syntax errors.
Run the program and check if it gives unexpected results.
Example:
result = sum_of_squares(3)
Output:
result = 12
Expected should be 1^2 + 2^2 + 3^2 = 14.
Since output is wrong, we start debugging.
2. Setting Breakpoints
Breakpoints tell MATLAB where to pause execution so you can check the code line by line.
How to set:
• Click on the left margin next to the line number in the Editor window.
(A red dot appears.)
• Or use the command:
• dbstop in sum_of_squares at 3
Example:
Set a breakpoint at the line:
total = total + i*2;
3. Running with Breakpoints
Run the program again:
result = sum_of_squares(3)
MATLAB will pause execution at the breakpoint before executing that line.
4. Examining Values
Now, check the values of variables when the program pauses.
You can:
• Hover the mouse over variables in the Editor to see their values, or
• Type in the Command Window:
• disp(i)
• disp(total)
You’ll see:
i=1
total = 0
After one iteration, check again:
i=2
total = 2
You realize that instead of squaring i, the program multiplies i by 2.
5. Correcting and Ending Debugging
Once the error is identified:
• Click Quit Debugging or type:
• dbquit
• Stop execution and correct the code:
• total = total + i^2;
6. Correcting the M-file and Verifying
Save the corrected file and run again:
result = sum_of_squares(3)
Output:
result = 14
Correct result obtained.
Summary of Debugging Commands
Command Description
dbstop in filename at lineno Set a breakpoint
dbstatus Show current breakpoints
dbclear all Clear all breakpoints
dbstep Execute the next line
dbcont Continue execution until next breakpoint
Command Description
dbquit Exit debugging mode
Conclusion
By using breakpoints and examining variable values step-by-step, you can easily identify
logic or runtime errors in MATLAB M-files. Debugging helps ensure that your program
produces accurate and reliable results.
Flowchart
Step-by-step demonstration showing how to set a breakpoint, run a MATLAB program
in debug mode, and use the debugging tools to find and fix an error.
Example Program (with error)
Save this as sum_of_squares.m:
function total = sum_of_squares(n)
total = 0;
for i = 1:n
total = total + i*2; % Wrong: should be i^2
end
end
We expect the sum of squares (1² + 2² + 3² = 14 for n=3),
but this code mistakenly multiplies by 2 instead of squaring.
Step-by-Step Demonstration
1. Open the File
Open sum_of_squares.m in the MATLAB Editor.
2. Set a Breakpoint
A breakpoint pauses the program execution at a specific line.
Ways to set a breakpoint:
• Graphically: Click on the gray margin next to the line number (a red dot appears).
→ Set it on this line:
• total = total + i*2;
• Command Line Method:
• dbstop in sum_of_squares at 3
(Here, line 3 is the line inside the for loop.)
3. Run in Debug Mode
Now, run your program:
result = sum_of_squares(3)
The program will pause at the breakpoint before executing that line.
You’ll see:
K>> % MATLAB prompt changes to “K>>” (debug mode)
and a yellow arrow appears next to the line being executed.
4. Examine Variable Values
At this point, you can check the values of variables.
Methods:
• Hover your mouse over variables i and total in the Editor.
MATLAB shows their current values.
• Or type in the Command Window:
• disp(i)
• disp(total)
You’ll see:
i=1
total = 0
After continuing execution:
dbstep
You’ll find that total increases by 2 instead of 1², 2², etc.
5. Identify the Error
You realize that the logic i*2 is wrong — it should be i^2 to calculate squares.
6. End Debugging
To stop debugging:
dbquit
Or click “Quit Debugging” ( Stop button) in the Editor toolbar.
7. Correct the Error
Edit the M-file:
total = total + i^2;
Save the file.
8. Clear Breakpoints and Re-run
dbclear all
Run the corrected program:
result = sum_of_squares(3)
Output:
result = 14
Correct result obtained.
How Debugging Helps Identify Logical Errors in M-files
Logical errors are often the most challenging to detect because the program runs successfully
but gives wrong or unexpected output. Here’s how the debugging process helps uncover
them:
1. Use MATLAB’s Built-in Debugger
MATLAB provides a powerful interactive debugger that allows you to:
• Set breakpoints: Click on the dash (-) next to a line number in the Editor to pause
execution at that line.
• Step through code: Use Step, Step In, and Step Out to execute code line by line.
• Inspect variables: While paused, you can hover over variables or check the Workspace
to see their current values.
2. Compare Expected vs. Actual Output
• Define test cases with known inputs and expected outputs.
• Run the M-file with those inputs.
• If the actual output differs, use the debugger to trace where the computation goes
wrong.
Example:
If a function is supposed to compute the average but returns the sum, stepping through
reveals that the division by n is missing.
3. Add Diagnostic Print Statements (Temporary)
Insert disp() or fprintf() statements to print intermediate values:
disp(['Value of x at line 10: ', num2str(x)]);
This helps track variable values without using the debugger—useful for loops or complex
flows.
Note: Remove or comment out these statements after debugging.
4. Check Loop and Conditional Logic
Logical errors often occur in:
• Off-by-one errors in loops (for i = 1:n vs. for i = 1:n-1)
• Incorrect conditions in if statements (> instead of >=)
• Misplaced logic inside or outside loops
Use the debugger to:
• Verify loop bounds
• Confirm that conditions evaluate as expected
• Ensure correct branches are taken
5. Use the “Run and Time” or Profiler (for performance-related logic)
While not directly for correctness, MATLAB’s Profiler (profile on, run code, profile viewer)
can reveal unexpected function calls or repeated operations that hint at flawed logic.
6. Validate with Unit Tests
Write simple test scripts that call your function with edge cases (e.g., empty inputs, zeros,
negative numbers). If a test fails, use debugging to investigate.
% test_myFunction.m
assert(myFunction(2,2) == 4, 'Basic case failed');
assert(myFunction(0,5) == 0, 'Zero input failed');
Debugging is a systematic process used to identify, locate, and fix errors (bugs) in code. In
MATLAB, M-files (.m files) can contain logical errors—mistakes in the program’s logic that
cause it to produce incorrect results, even though the code runs without syntax errors or
runtime crashes.
How Debugging Helps Identify Logical Errors in M-files
Logical errors are often the most challenging to detect because the program runs successfully
but gives wrong or unexpected output. Here’s how the debugging process helps uncover
them:
1. Use MATLAB’s Built-in Debugger
MATLAB provides a powerful interactive debugger that allows you to:
• Set breakpoints: Click on the dash (-) next to a line number in the Editor to pause
execution at that line.
• Step through code: Use Step, Step In, and Step Out to execute code line by line.
• Inspect variables: While paused, you can hover over variables or check the Workspace
to see their current values.
Why it helps: By observing how variables change during execution, you can spot where the
logic deviates from expected behavior.
2. Compare Expected vs. Actual Output
• Define test cases with known inputs and expected outputs.
• Run the M-file with those inputs.
• If the actual output differs, use the debugger to trace where the computation goes
wrong.
Example:
If a function is supposed to compute the average but returns the sum, stepping through
reveals that the division by n is missing.
3. Add Diagnostic Print Statements (Temporary)
Insert disp() or fprintf() statements to print intermediate values:
matlab
1
disp(['Value of x at line 10: ', num2str(x)]);
This helps track variable values without using the debugger—useful for loops or complex
flows.
Note: Remove or comment out these statements after debugging.
4. Check Loop and Conditional Logic
Logical errors often occur in:
• Off-by-one errors in loops (for i = 1:n vs. for i = 1:n-1)
• Incorrect conditions in if statements (> instead of >=)
• Misplaced logic inside or outside loops
Use the debugger to:
• Verify loop bounds
• Confirm that conditions evaluate as expected
• Ensure correct branches are taken
5. Use the “Run and Time” or Profiler (for performance-related logic)
While not directly for correctness, MATLAB’s Profiler (profile on, run code, profile viewer)
can reveal unexpected function calls or repeated operations that hint at flawed logic.
6. Validate with Unit Tests
Write simple test scripts that call your function with edge cases (e.g., empty inputs, zeros,
negative numbers). If a test fails, use debugging to investigate.
% test_myFunction.m
assert(myFunction(2,2) == 4, 'Basic case failed');
assert(myFunction(0,5) == 0, 'Zero input failed');
Example: Debugging a Logical Error
Faulty M-file (average.m):
function avg = average(vec)
total = 0;
for i = 1:length(vec)
total = total + vec(i);
end
avg = total; % Forgot to divide by length!
end
Debugging steps:
1. Call average([1 2 3]) → returns 6 instead of 2.
2. Set a breakpoint inside the function.
3. Step through: see total = 6 at the end.
4. Notice avg = total — missing division.
5. Fix: avg = total / length(vec);
Debugging identifies logical errors in M-files by:
• Allowing step-by-step execution and variable inspection
• Enabling comparison between expected and actual behavior
• Revealing incorrect assumptions in loops, conditions, or formulas
By combining MATLAB’s debugging tools with careful testing and observation, you can
systematically isolate and correct logical flaws in your code.
Steps to Set a Breakpoint in MATLAB Editor
1. Open the M-file in the MATLAB Editor.
2. Click on the dash (-) to the left of the line number where you want execution to pause.
• A red dot or box appears, indicating a breakpoint is set.
3. Run the script or function — execution will stop at the breakpoint.
(Optional: You can also set a breakpoint by pressing F12 with the cursor on the desired line,
or by using the dbstop command in the Command Window.)