We end with a few of our favorite easy-to-explain, but highly valuable and generally rarely seen MATLAB tips:

Tip: Log your MATLAB session

It can be extremely helpful in certain cases to log a MATLAB session or the run of some job; this can be achieved using the diary command.

Tip: Check your code

Although MATLAB is a weakly and dynamically typed language, if you have ever used the integrated MATLAB editor, you'll perhaps have seen some of the feedback it gives you on your code, covering both possible errors to possible performance improvements. This is known as static analysis, and is a little like type-checking ino many compiled languages, but is not part of the language itself. This same functionality can be obtained from a non-graphical environment at a MATLAB terminal using the checkcode command. Note that if checkcode finds no potential issues, there will not be any output displayed to indicate success.

Tip: Preallocate arrays

This is quite an easy way to improve performance. When you know the eventual size of say, a cell array, use cell(m,n,...) instead of just {} to create the cell array. Similarly you can use the ones, zeros, or nan functions for numeric matrices and arrays, and there is a method for sparse matrices as well.

Tip: Generate HTML documents from MATLAB Code

Publishing MATLAB code from the editor is a bit like literate programming, with some MATLAB and HTML-specific tooling; it is useful if you wish to publish your code in a readable format.

Tip: Serialize data

Many users may be familiar with MATLAB's save and load commands for saving and loading individual variables, sets of variables, or entire workspaces. However, these functions use the undocumented functions getByteStreamFromArray and getArrayFromByteStream under the hood, which can be highly useful if you do not want to save data to disk immediately. For instance, maybe you wish to implement a custom hashing function or send the data over the wire in a custom parallel toolkit, perhaps one that interfaces with another language. A word of warning: the serialized data may be version-dependent, so only use it for the same version of MATLAB.

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement