Customize dbstop in MATLAB

debugging, matlab

Solution

The problem with using the form "DBSTOP in FILESPEC if EXPRESSION" of `dbstop` is that it sets a breakpoint only at the first line of the file. A solution is to use the form "DBSTOP in FILESPEC at LINENO if EXPRESSION" to set a breakpoint at each line.

Consider the following example script, saved on a file called `testfile.m`.

clear all
for m = 1:10;
    k = 2*m
end

Say we want to stop if variable `k` exceeds the value `6`. We first automatically set the breakpoints in all lines of this file:

file = 'testfile.m';
varname = 'k';
expression = 'k>6'; %// it should be 'exist(''k'')&&k>6', but that's added later

%// Determine number of lines of file:
fid = fopen('testfile.m');
cont = 1;
nlines = 0;
while cont
    readline = fgetl(fid);
    cont = ~isequal(readline,-1);
    nlines = nlines + cont;
end
fclose(fid);

%// Set breakpoint at each line. We need eval for this
for n = 1:nlines
    eval(['dbstop in ' file ' at ' num2str(n) ' if ( exist(''' varname...
        ''') && ( ' expression ' ) )'])
end

Now, after running the above (check that every line of `testfile.m` has a yellow breakpoint), run `testfile` and check values when it stops:

This is admittedly a little cumbersome if you have several variables or files. Also, I'm not sure how many simultaneous breakpoints Matlab supports (we are using one for each program line).

Problem

Is it possible to add a customized `dbstop` condition to Matlab? Recently I found myself with out of bounds values in multiple variables, one way to track down the first occurance of this would be to set a conditional breakpoint on each line where these values are updated. However, I hope there is an easier way to do this. I have recently had to track down a `NaN` which was fairly trivial due to: ``` dbstop if naninf ``` Hence I hope that it is possible to get something like: ``` dbstop if anything outside myBound ``` or ``` dbstop if myVariable outside myBound ``` I would of course be willing to take the performance hit that one may expect.

Original source