Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB debugging: smarter way to stop the code with an specific condition?

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?

like image 530
Ander Biguri Avatar asked Dec 01 '15 18:12

Ander Biguri


People also ask

How do you set conditional breakpoints in MATLAB?

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.

Which function can be used to terminate the debug mode MATLAB?

dbquit terminates debug mode.

What is the special debugging tool in MATLAB?

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.

What are debugging methods in MATLAB?

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 .


1 Answers

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:

enter image description here

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.

More things

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!

like image 121
Ander Biguri Avatar answered Sep 21 '22 23:09

Ander Biguri