Skip to content

Matlab best practices

Jeffrey Markowitz edited this page Sep 1, 2013 · 4 revisions

For a comprehensive over that's not too long (36 pages, you can get through it in a few hours!) look here.

Text formatting / Commenting

Comment early and often when you need to. That is, comment enough so that someone else, or yourself 10 years down the road, can understand the data. Avoid the urge to win an ascii art contest. Look to some established MATLAB packages for a good sense of how much is too much or too little.

Variables / Data structures

Again, use CamelCase or underscore case. Keep it consistent.

Data, files and folders hierarchy

Keep your data files small enough so that your scripts don't get bogged down in file i/o. This will speed up your feedback loop, and avoid a wait-ten-minutes-before-finding-the-bug situation. Obey standard naming conventions for dates in your filenames, e.g. use the YYMMDD format or YYYYMMDD.

Functions / Modularity

Each function or script should compute one self-contained function, and ideally should by less than 100 lines long (this isn't a hard and fast rule, but do try to stay under the limit when you can).

Debugging / Testing

Get well acquainted with the MATLAB debugger. Make sure to test your code on "toy" or simulated inputs where you know what the output should be (ideally you should know what the answer should be exactly, so that it can be confirmed numerically).

Plotting data

  • Use export_fig to save figures nicely to a number of vector & bitmap formats. Great for presentations, publications, and posters.

Speed and memory

  • Use MATLAB Profiler to find computational bottlenecks
  • Pre-allocate large data (for example, arrays) for speed
  • Avoid loops by code vectorization

Code examples

Code examples are in the repository.