Matlab Style Guide

Here is my personal take on a simple and practical Matlab Style Guide that provides code formatting guidelines for Matlab code.

General

Code shall be formatted to maximise readability, and to avoid coding mistakes.

Follow the recommendations from Matlab Code Analyzer, so there are no warnings (yellow markers on the bar on the editor's right side) in the code.

Avoid creating scripts, make functions instead. (To ensure separate namespaces for each code file.)

Indentation and alignment

Code shall be indented using 4 spaces, and otherwise as suggested by the Smart Indent feature, or in a way that improves code readability.

Avoid trailing spaces (blanks after content before line break).

Do not align variable assignments (on purpose):

a_long_name = 1
b = 2
c = 4

Variable names

Variable names should be meaningful and relevant, try to avoid names like 'tmp'.

Variable names that are short (1-3 characters) should only be used in a local scope, such as loops or conditional branches.

Spacing

In general, insert spaces around operators:

a >= b
1 + 2 == 3
b = c
3 * 4 / 2

The colon operator is an exception, the following are all acceptable, though variants with more spacing are easier to read:

1:10
1:end-1
1:end - 1
1 : end - 1
b+1:b+10
b + 1:b + 10
b + 1 : b + 10
1.25 * (0:299)

Insert space after comma and semicolon, e.g., when specifying indices or defining arrays:

a(1, 2)
b = [1, 2, 3]
c = [1; 2; 3]

Insert comma between elements in arrays:

a = [1, 2, 3]

Statements

Avoid multiple statements on a single line, e.g., put each variable assignment on a single line.

Also, conditional statements should not be stated on a single line, use multiple lines:

if a > 10
    b = 1
end

Comments

Insert one space after comment symbol (%) before the comment text. For comments following a code statement (same line), insert two spaces before comment symbol.

A comment should describe why the code is needed, or explain magic numbers (such as choice of indices, or constant values).

% calculate the flux
f = 201 / surface_area;  % 201 is the flow rate

Line breaking

Break lines (using ellipses ...) longer than 80 characters. Suggested breakpoints:

Before or after a parentheses

a = sin(...
    12)

b = c + ...
    (d + e)

After an operator

f = (g + 100 + ...
    - 99 - 1)

a = b & ...
    c * 2

Other style guides

Here are some additional resources with alternative (and more comprehensive) guidelines: