M Files

Modularize

The best way to write a big program is to assemble it from well designed small pieces (usually functions). This approach enhances readability, understanding and testing by reducing the amount of text which must be read to see what the code is doing. Code longer than two editor screens is a candidate for partitioning. Small well designed functions are more likely to be usable in other applications.

Make interaction clear

A function interacts with other code through input and output arguments and global variables. The use of arguments is almost always clearer than the use of globals. Structures can be used to avoid long lists of input or output arguments.

Partitioning

All subfunctions and many functions should do one thing very well. Every function should hide something.

Use existing functions

Developing a function that is correct, readable and reasonably flexible can be a significant task. It may be quicker or surer to find an existing function that provides some or all of the required functionality. The file exchange on MATLAB Central is an excellent resource.

Any block of code appearing in more than one m-file should be considered for packaging as a function

It is much easier to manage changes if code appears in only one file.

Subfunctions

A function used by only one other function should be packaged as its subfunction in the same file. This makes the code easier to understand and maintain.

Test scripts

Write a test script for every function. This practice will improve the quality of the initial version and the reliability of changed versions. Consider that any function too difficult to test is probably too difficult to write. Boris Beizer: “More than the act of testing, the act of designing tests is one of the best bug preventers known.”