When it comes to debugging I prefer the approach described by
Brian Kernighan and Rob Pike in "The Practice of Programming":
"... we find stepping through a program less productive than
thinking harder and adding output statements and
self-checking code at critical places. Clicking over
statements takes longer than scanning the output of
judiciously-placed displays. It takes less time to decide where
to put print statements than to single-step to the critical
section of code, even assuming we know where that is. More
important, debugging statements stay with the program;
debugging sessions are transient."
To allow for debugging statements that stay with the program and can be switched on and off, I wrote two very simple Matlab functions
(t_debug.m, print_debug.m
). Here is how they work:
>> t_debug on >> print_debug('t_debug is on'); DEBUG: t_debug is on >> t_debug DEBUG state: 1 >> t_debug off >> print_debug('This should not print'); >> t_debug offff Warning: USE: debug(mode) with mode='on', 'off', or a numeric value to set debugging to a certain level. You used 'offff'. > In t_debug at 54 >> t_debug(10) >> print_debug('t_debug prints up to level 10', 9) DEBUG: (L=9) t_debug prints up to level 10 >> print_debug('t_debug prints up to level 10 (this won''t print)', 11) >> print_debug('t_debug prints up to level 10') DEBUG: t_debug prints up to level 10 >> t_debug DEBUG state: 10
In t_debug
I make use of the global preferences by introducing a group 'runmode' with preference 'debug' that's being set to
'true' or 'false' or 'number' when debug is 'on' or 'off' or N, respectively. print_debug
checks the state of 'debug' in 'runmode' and
displays the text it get's as a parameter:
PRINT_DEBUG To set a program to debug mode use: t_debug on To exit debug mode: t_debug off To use multi-level debugging output: t_debug(N) %where N=0..inf print_debug(...,level) %where level <= N Here, N=0 represents 'off', i.e. no debugging output, N=1 and N=inf represents 'on', i.e. full debugging output
Download at Matlab File Exchange.
ronni <at> gi <dot> alaska <dot> edu | last changed: November 22, 2010