# MATLAB Style Guide
The following summary style guide has been adapted from *The elements of MATLAB style* by Richard Johnson [1] to distill the most important elements. Deviations from Johnson's style are marked with (†).
## General
Avoid causing confusion! Emphasize the following characteristics in your code:
- Simplicity
- Clarity
- Completeness
- Consistency
- Robustness
Avoid throw-away code. Everything you save in an `.m` file could be used again by you or somebody else. If it's worth saving, it's worth cleaning up to meet these style guides.
Following these principles helps the reader, which could be a stranger or a future you. The time taken to refactor code often saves far more time that might have been spent trying to understand or troubleshoot poorly written code.
Finally, document any intentional style deviations. You are allowed to break any of the rules in this guide, as long as you justify and document why you have done so.
# MATLAB Style, Part 1: Formatting
**General**
Format the code to make it more readable. Avoid long lines and multiple statements per line so that the code is easier to scan. Indent consistently to reveal logical structure. Use spaces consistently in appropriate places to make each line easier to read and interpret. In particular, insert spaces around operators and expressions to reveal the structure and meaning of statements. Write your code in logical blocks that can be read as paragraphs so that the program can be understood in chunks.
## 1.a. Line length
Lines should be no longer than 80 characters. Split long code lines at graceful points (commas, spaces, operators), and use one or more subexpressions on multiple lines rather than a single complicated expression where possible.
## 1.b. Indentation
Indentation should be 4 spaces and used consistently to structure code blocks. Avoid deeply nested indentation blocks and use subfunctions where appropriate.
## 1.c. Whitespace
(†) Use a single whitespace around all commas and operators. Do not use whitespace around parentheses, colons or semicolons.
## 1.d. Alignment
Align multiple lines with whitespace padding only if it enhances readability. In general, do not align operators or assignments across multiple statements.
```matlab
% avoid unnecessary whitespace padding between lines
row = 3;
column = 4;
diagonal = 5;
% use consistent operator spacing instead
row = 3;
column = 4;
diagonal = 5;
```
## 1.e. Code groups
Break code into logical groups by leaving one blank line between statements of different types (e.g. assignment statements and operational statements), and two blank lines between different functional code sections (e.g. an initialisation block and a looping block).
# MATLAB Style, Part 2: Naming conventions
## 2.a. lowerCamelCase variable and function names
Use lowerCamelCase style for general variable and function names, e.g. `velocity, angularAcceleration`.
## 2.b. Variable name length
Variable and function names should be at least three characters long, except when the scope of the variable is small, such as in a mathematical expression in a subfunction.
## 2.c. Numeric prefix
Use the prefix `n` for variables representing a number, e.g. `nFiles, nSegments` rather than `numFiles, numberOfSegements`. Using prefix `m` is permitted in the context of matrix dimensions.
## 2.d. Loop counters
Avoid using `i` and `j` as indices or loop counters. Where loops are nested, consider using `i, j, k` as a prefix for iterator variables, e.g.
```matlab
for iFile = 1:nFiles
for jLine = 1:nLines
% ...
end
end
```
## 2.e. Shadowing names
Avoid variable and function names that shadow built-in functions or objects from a higher scope.
## 2.f. Readability
Variable and function names should be readable and relevant to their use. Avoid ambiguous abbreviations or acronyms, and don't use / re-use a variable name outside the intended context.
## 2.g. Numbers
Avoid using numbers in variable or function names, particularly to denote version (e.g. `foo1, foo2`), with the exception of the common case of "2" in place of "to" in functions such as `rad2deg`.
## 2.h. Scope of constants
Limit the scope of hard-coded constant values. Where constants are necessary in a larger scope, create a function to return that value instead (e.g. `pi`).
## 2.i. Uppercase constants
Constants specific to a single `.m` file should be written in uppercase, with a single underscore to separate, e.g. `MAX_ITERATIONS = 10`.
## 2.j. UpperCamelCase structures
Use UpperCamelCase style for structures, e.g. `Segment, JointTrajectory`.
## 2.k. Structure field names
Fieldnames of structures should follow general variable name conventions, and should not repeat the name of the parent structure.
## 2.l. Function prefixes
Use prefixes in functions consistently:
- `find...` should return an index and / or the value at that index
- `is...` should be reserved for boolean functions
- `get/set...` should be reserved for setting or retrieving object properties
## 2.m. Classes
Classes and objects should be named the same way as structures, properties the same way as variables, and methods the same way as functions.
# MATLAB Style, Part 3: Documentation and comments
## 3.a. Useful comments
Make comments useful. Avoid simply restating what the code does, but describe why or how it works. Ensure comments are up-to-date with the actual code.
## 3.b. Function and class documentation
All functions and class definitions require header comments that support the behaviours of the inbuilt `help`, `lookfor` and `doc` functions.
- For functions, the H1 line must be a short fragment summarising the behaviour, with a capitalised first letter and ending with a period. The subsequent lines should show and describe usage examples of all supported combinations of input and output variables, where the displayed variable names should match the function variable names. Bonus points for using `See also` and hyperlinks to more information. See also: [How to create help text for functions](https://www.mathworks.com/help/matlab/matlab_prog/add-help-for-your-program.html). An example function header is shown below.
- For classes, this includes at minimum a single line summary of the class, constructor and main public properties and methods. Bonus points for further documentation. See also: [How to create help text for classes](https://www.mathworks.com/help/matlab/matlab_prog/create-help-for-classes.html).
```matlab
[a, b] = myExampleFunction(x, y, z)
% Combines scalar values in some exemplary way.
% a = myFunction(x, y) combines scalar inputs x and y
% in some way to create a scalar output a.
% [a, b] = myFunction(x, y) additionally returns a vector
% b as some combination of x, y and a.
% myFunction(..., z) optionally takes a third scalar z
% which offsets the returned values in some way.
```
## 3.c. Attribution
Any attribution, versioning or licensing comments should be separated by a new line from the header so it does not appear in the help text. In general, avoid documenting authorship or version if it is already contained in the version control system.
## 3.d. Restrictions
Enforce restrictions in code, not comments.
```matlab
% beta must be greater than 0 <-- avoid
% replace with:
assert(beta > 0, 'myFunction:Beta', 'beta must be greater than 0.');
% make sure b is between a and c <-- avoid
% replace with:
b = max(b,a);
b = min(b,c);
```
## 3.e. Dead code
Delete code rather than commenting it out. Where commented code blocks are used to show example behaviour of a program, consider moving it into an executable example script, function help text or external markdown documentation.
## 3.f. In-line comments
Avoid end-line comments in favour of comments in a separate line directly before the associated code.
## 3.g. Comment indentation
Comments should be indented to match the associated program code, with a single whitespace after the comment sy