When I debug long pieces of numerical code, often I want to see the function variable values if something happens, or in an specific iteration. Generally I do:
function banana(platano)
% long stuff here
for ii=1:123456789
% tons of maths
if ii==45612
stophere=1; % I put a break point in this line of code
end
end
However, this requires me to write code in the function for debugging and it doesn't look nice. Is there a smarter way of doing this?
To set a conditional breakpoint, right-click the gray area to the left of the executable line where you want to set the breakpoint and select Set Conditional Breakpoint. If a breakpoint already exists on that line, select Set/Modify Condition. In the dialog box that opens, enter a condition and click OK.
dbquit terminates debug mode.
MATLAB has a “debugger” that helps you locate and correct that line of code. The debugger allows you to set breakpoints (that tell MATLAB to pause in a kind of “suspended animation” when it reaches that line. You can then tell MATLAB to execute the code one step at a time.
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 .
One of the ways is using Conditional Breakpoints. You can add them by right clicking on the number of the line and selecting the "Set conditional Breakpoints..."
option.
Example:
As described in the comments of this answer, if you want to set it with the command line you can use
dbstop in filename at linenumber if condition
As an example:
dbstop in banana at 6 if ii==454345433
note, that the at linenumber
and if condition
are optional.
Another useful tool of the debugger is breaking the program if there has been an error, using dbstop if error
, as show in this Q&A.
Thanks to @Dev-il for showing me this!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With