recipes : programming : Debugging

Problem

How do I de-bug my code?

Solution

There is a long documentation page on debugging. The MATLAB code editor has extensive facilities for adding breakpoints, stepping through code one line at a time, etc. Even if you're not using the MATLAB editor, you have access to the de-bugging functions. For example, you can insert the keyboard command into your m-file at the point where you think stuff is going wrong. When the command is reached, execution of the m-file stops and you are able to type in commands and examine variables. The dbquit command resumes execution of the m-file.

Discussion

You have access to lots of de-bugging functions from the MATLAB editor. Even you don't use it, you can still roll you own solution using commands like keyboard or even just by allowing the output of your calculations to be displayed on the command line as the program progresses. You can also use "dbstop if error" to cause MATLAB to enter debugging mode only when an error is encountered.