Editing and Debugging

The Editor

Matlab has a built-in editor.

Benefit: Integration with the command processor. When a crash occurs, you can inspect variables in the editor.

Editor Tips

Cell mode

  • 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.)

Comments

  • Use lots of comments to make your code readable.
  • Block comments are enclosed with %{...%}

Mlint

  • highlights questionable syntax or errors

Debugging

Debugging means locating program errors.

keyboard command

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.

Debugging mode

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 dbstop error

To end debugging mode type dbclear all

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 dbquit This stops the program.

Tips

Write test functions for every sub-routine you write. Never assume that a new program will run correctly.

Write a 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.