Editing and Debugging¶
Matlab has a built-in editor.
Benefit: Integration with the command processor. When a crash occurs, you can inspect variables in the editor.
- Start a line with
%%and it becomes a collapsible
cell. That makes moving around the editor easier.
- One can do other things with cells (e.g., run a portion of code; collapse it; etc.)
- Use lots of comments to make your code readable.
- Block comments are enclosed with
- highlights questionable syntax or errors
Debugging means locating program errors.
A useful command for debugging is keyboard. It halts program execution and returns the user to the command line. Any commands can then be executed as if the program itself contained those commands. In particular, one can inspect the values of all local variables.
Setting break points has a similar effect.
Matlab can switch to a debugging mode that allows the user to inspect the state of a program when it crashes.
To switch on debugging mode, type
To end debugging mode type
When a program crashes, it is halted and the command prompt is activated.
The effect is exactly the same as placing a
keyboard statement at the point where the program crashed.
To end debugging, type
This stops the program.
Write test functions for every sub-routine you write. Never assume that a new program will run correctly.
test_all functions that runs all the tests in one go.
Embed self-test code in your programs.
Check everything you can.¶
- Is the number of input arguments correct?
- Are the input arguments of the right type and dimension?
- Are they in admissible ranges?
- Are intermediate results admissible?
- Are the output arguments acceptable?
By checking all the time, errors are spotted as early as possible which makes them much easier to fix.
See validateattributes for an easy way of implementing all of this.