Layout

The purpose of layout is to help the reader understand the code. Indentation is particularly helpful for revealing structure.

Content should be kept within the first 80 columns

Files that are shared between several people should keep within these constraints. Readability improves if unintentional line breaks are avoided when passing a file between programmers. Seventy five columns is the MATLAB editor default, so keeping within 75 columns will ensure compatibility with most other users if your organization doesn't have a standard.

Lines should be split at graceful points

Split lines occur when a statement exceeds the suggested 80 column limit.

In general:

  • Break after a comma or space.
  • Break after an operator.
  • Align the new line with the beginning of the expression on the previous line.
totalSum = a + b + c + …
           d + e;
function (param1, param2,…
          param3)
setText ([‘Long line split’ …
          ‘into two parts.’]);

Basic indentation should be 3 or 4 spaces

Good indentation is probably the single best way to reveal program structure.

Indentation of 1 is too small to emphasize the logical layout of the code. Indentation of 2 is sometimes suggested to reduce the number of line breaks required to stay within 80 columns for nested statements, but MATLAB is usually not deeply nested. Indentation larger than 4 can make nested code difficult to read since it increases the chance that the lines must be split. Indentation of 4 is the current default in the MATLAB editor; 3 was the default in some previous versions.

Indentation should be consistent with the MATLAB Editor

The MATLAB editor provides indentation that clarifies code structure and is consistent with recommended practices for C++ and Java.

In general a line of code should contain only one executable statement

This practice improves readability and allows JIT acceleration.

Short single statement if, for or while statements can be written on one line

This practice is more compact, but it has the disadvantage that there is no indentation format cue.

if(condition); statement; end
while(condition); statement; end
for iTest = 1:nTest; statement; end