This page gives a quick introduction into how to locate errors in Matlab functions (including those of the NeuroElf toolbox, I never claimed the toolbox is 100 per cent error free !)
While reviewing and testing code is part of the development and implementation process, it still is a common phenomenon that some part of the code that used inside a function or batch file creates an error (usually aborting the current computation and returning to the Matlab prompt with a sometimes cryptic message) or produces an erroneous result (e.g. the result of a specific operation is known but the function that should provide that result delivers a different one instead).
It is often complicated to interpret an error message correctly and find the problematic passage in the code, and this page should give some first pointers about how to do this.
Matlab must be started with Desktop and Java VM enabled to fully use the procedures mentioned here. Also, you should familiarize yourself with the commands (and also keyboard shortcuts!) associated with the most important Matlab debugging functions.
The following commands can be employed to locate erroneous code:
dbstep
- executing the next instruction, not traversing into the code of any M-file (batch or function)dbstep in
- executing the next instruction and, if required, open the code of any M-file being used (in order of execution)dbstep out
- executing the remainddbstop
/ dbclear FUNCTION_NAME LINE_NUMBER
- setting/removing unconditional breakpointsdbstop FUNCTION_NAME [LINE_NUMBER] if 'CONDITION
' - setting conditional breakpoints (condition tested in the local workspace)dbstop if error
- intercept any error that would mean program terminationdbstop if all error
- intercept any exception (error message), even those that are caught by try, STATEMENT, catch, ERROR_HANDLER, end
blocksdbup
and dbdown
- change the workspace of inspection to peek into variables used by the caller function (helpful if you suspect that the error occurred “up the chain”) and back downIf a function (or batch file) produces an error (error message), the first things to do are
dbstop if error
or dbstop if all error
and then re-running the function)sum
)This is a much trickier situation. If you don't have any clear suspicion about what is happening, it is useful to follow the arguments you pass into a function (or that are created by batch files) and first locate the approximate location of an error. For invalid results, a typical thing to do is to check whether variables contain bad values:
% test if variable timeseries contains problematic values any(isinf(timeseries(:)) | isnan(timeseries(:))
Such bad values very commonly disrupt normal behavior of functions.
If you are unable to locate the error and the function you suspect is causing the problem is part of NeuroElf, please feel free to get in touch with me. In that case, others can most likely benefit from this by having more reliable functions in an upcoming version of the toolbox!