Debug MATLAB Code Files
Since R2021b. Replaces Debug a MATLAB Program (R2021a) and Debug Code in the Live Editor
(R2021a).
You can diagnose problems in your MATLAB code files by debugging your code interactively in the
Editor and Live Editor or programmatically by using debugging functions in the Command Window.
There are several ways to debug your code:
• Display output by removing semicolons.
• Run the code to a specific line and pause by clicking the
Run to Here button.
• Step into functions and scripts while paused by clicking the
Step In button.
• Add breakpoints to your file to enable pausing at specific lines when you run your code.
Before you begin debugging, to avoid unexpected results, save your code files and make sure that the
code files and any files they call exist on the search path or in the current folder. MATLAB handles
unsaved changes differently depending on where you are debugging from:
• Editor — If a file contains unsaved changes, MATLAB saves the file before running it.
• Live Editor — MATLAB runs all changes in a file, whether they are saved or not.
• Command Window — If a file contains unsaved changes, MATLAB runs the saved version of the
file. You do not see the results of your changes.
Display Output
One way to determine where a problem occurs in your MATLAB code file is to display the output. To
display the output for a line, remove the semicolon from the end of that line. In the Editor, MATLAB
displays the output in the Command Window. In the Live Editor, MATLAB displays the output with the
line of code that creates it.
For example, suppose that you have a script called plotRand.m that plots a vector of random data
and draws a horizontal line on the plot at the mean.
n = 50;
r = rand(n,1);
plot(r)
m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')
To display the output of the rand function at line two, remove the semicolon at the end of the line.
MATLAB displays the value of r in the Command Window.
22 Debugging MATLAB Code
22-2
Précédent

- 776/1450

Suivant