Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

Debugging Approaches

There are lots of posts on the MATLAB newsgroup asking questions like why do I get this error "xxx"? One of the most common answers shows users how to track down the information for themselves.

Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime.

This entails learning to use the MATLAB debugger.

Contents

Ways to Debug

There are probably a lot of ways to debug programs. I am going to mention the ones that come to me quickly. These include:

Discussion

Now that MATLAB has a great debugger (whether you use the commands or use the tools provided in the MATLAB Editor), I now longer use the technique where I edit my code. It's too easy to not remember all the spots I edited and have them revert, except for my bug fix, when I'm done.

If I'm not sure where the bug is, guessing where to place a breakpoint sometimes doesn't always work well. In those cases, I generally set dbstop if error> and see where things have gone wrong. From there, I can backtrack as needed, sometimes using the technique of setting a breakpoint at the top of the function which elicited the error. I can then run again and step through from the top. Sometimes I have to backtrack to other functions on the call stack, but at least I have a point of reference by then.

Since I often work from the editor, rather than the command-line, I automatically see the code analysis messages. I do find it useful sometimes to do a side-by-side comparison of two versions of a file and I generally do so from the editor Tools menu.

Ancillary Technique

We've all heard the adage "a picture's worth a thousand words." With that in mind, instead of just looking at the code or variable values, I frequently find myself plotting interesting variables to get a quick look. Often I can tell from a quick plot exactly which variable is incorrect and that then helps me narrow down where to look for the bug.

How Do You Debug?

Do you have some helpful debugging techniques to share? I'd love to hear them here.




Published with MATLAB® 7.10


  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.