Getting in to someones code or just cleaning up your own Matlab code it’s good to know how to do break points and other useful to make the process flow a bit smoother. I thought I would do a list of my favorites for making my code work faster and with less tedious work.
The best debug command in Matlab: dbstop if error
Scenario: Some error happens in some file that is called by the main program which causes it to terminate with some cryptic error about some of the variables.
Since you probably modularized your code your usual procedure would be to to a disp command for the specific variable or set up a break point. This is oh so tedious but what if you could just acces the variable in the code or other variables that are in the scope at the moment!? You can with: dbstop if error. Just run it before executing your code and it will put you in the debug mode. The program will stop with the workspace full of the variables available when the error happened and you can easily tinker around with them to see what was the real problem in your implementation. After you are done just run dbquit in the command window and you will exit debug mode.
The Try-Catch statement
Matlab actually has a try-catch statement extremely useful when reading files or any other type of error prone procedure the statement looks like this
try // Your code here catch ERROR // Catching the error. ERROR contains the error information disp(ERROR); // Display the error object information. end
Where the ERROR is he ERROR object (you can call it what you want like THEBIGERROR or something else).
Setting breakpoints
In Matlab you can also set break points meaning that the code will stop at the point where you set the break point and let you access the variables available in the workspace at that particular point in time. You can even set conditional breakpoints which could be very useful in loops or value testing. Here are the most useful commands links go to the Matlab manual.
dbclear | Clear breakpoints |
dbcont | Resume execution |
dbdown | Reverse workspace shift performed by dbup, while in debug mode |
dbquit | Quit debug mode |
dbstack | Function call stack |
dbstatus | List all breakpoints |
dbstep | Execute one or more lines from current breakpoint |
dbstop | Set breakpoints for debugging |
dbtype | List text file with line numbers |
dbup | Shift current workspace to workspace of caller, while in debug mode |
(dbstep nlines – steps through code execution nlines at a time)
Other useful commands
lasterror – Gives an object with the error message, identifier and the stack from the last error occurred.
smart indent – just clears up the formatting of your code indenting the code in proper Matlab style.