Let's set up an example so you can see what's going on. I first make sure my debugger state is all cleared up and then create
a struct which I will then test to see if a particular field exists.
s.fred = 1;
1 function tf = isfieldTryE(s,f)
2 %ISFIELD True if field is in structure array.
3 % F = ISFIELDTRYE(S,'field') returns true
4 % if 'field' is the name of a field
5 % in the structure array S.
7 % See also GETFIELD, SETFIELD, FIELDNAMES.
9 tf = true;
11 tmp = s.(f);
12 catch E
13 % I don't care why it failed.
14 tf = false;
What happens if I ask to see if a particular field exists, and ask for MATLAB to stop if there's an error?
What you can see is that testing for either an existing or non-existent field sails on through.
And I get the same behavior if I try to stop only for an appropriate message identifier.
Caught-error breakpoint was hit in isfieldTryE at line 11. The error was:
Reference to non-existent field 'freddy'.
Now when I ask for a non-existent field, the debugger stops in the catch block. And to resume, I use
There are a few common issues that puzzle people when debugging. They include:
breakpoints disappearing when debugging. This is often caused by a clear all in code being run. See, for example, this post.
name collisions. These are caused either by using a variable name the same as a name for a MATLAB function, or having multiple
functions with the same name. Using which can help you figure out what's going on if you realize there's a nameclash.
variables not being present. This is often an issue of not understanding scoping in MATLAB, including inputs and outputs of functions, what workspace graphics callbacks execute in, scripts versus functions.
Here's a useful tip I use, for debugging, or sometimes to just find out the signature of a function. Using
dbtype 1 fileName
and you will see the first line of the file displayed. If you write your code as we tend to do at The MathWorks, the first
line of a file containing functions will be the function definition line. Voila, you have the signature!
Other Debugging Gotchas and Tips?
You might find some additional debugging tips on Doug's blog.
Some people like the keyboard command or omitting terminating semicolons but I prefer to debug without editing my code, when possible.
Do you have other tips to share that you find helpful? Post them here.