This style guide inspired by PEP8 for python and adapted for MATLAB.
This document provides coding conventions for MATLAB code. This style guide can/will evolve over time and is a reflection of my conventions.
The conventions presented in this document mostly agree with previously developed conventions.
Use 4 spaces per indentation level.
Indentations continuing long lines of code should add an extra level.
result = functionWithLongName(arg1, arg2, arg3, ...
arg4, arg5);
The closing parenthesis or bracket should be in-line (1) or the first character on a new line (2):
#1
result = functionWithLongName(arg1, arg2, arg3, ...
arg4, arg5);
#2
result = functionWithLongName(...
arg1, arg2, arg3, arg4, arg5 ...
);
Use indentation to separate keyword/name-value arguments from one another.
result = functionWithLongName(...
key1, value1, ...
key2, value2, ...
);
This is especially useful when there are multiple keyword/name-value arguments.
Multiline constructs (e.g., brackets, parenthesis) may either line up under the first non-whitespace character of the last line:
A = [...
1, 2, 3, ...
4, 5, 6, ...
7, 8, 9
];
or it may be included in the last line of the construct (similar to function arguments)
A = [...
1, 2, 3, ...
4, 5, 6, ...
7, 8, 9 ];
The first method is preferred for easier readability between commands.
Indent all functions - it's just easier to read.
% function
function n = addTwoNum(a, b)
n = a + b;
end
% class
class Person
properties
name = 'John';
end
methods
function greeting(obj)
fprintf('Hello, my name is %s\n', obj.name);
end
end
end
Spaces are preferred indentation.
Tabs should only be used with existing code using tab indentation.
Limit all lines to a maximum of 80. The MATLAB editor default is 75.
The line length (80) is standard for ASCII format.
To avoid exceeding the line length, use ...
result = functionWithVeryLongName(arg1, arg2, arg3, ...
arg4, arg5);
Use line breaks before binary operators.
income = [grossWages ...
+ taxableInterest ...
+ dividends ...
];
Use 2 blank lines around top-level definitions.
Use 1 blank line around local or nested definitions.
Use single blank lines sparingly inside functions or methods to indicate logical sections.
function m = computeSlope(x1, y1, x2, y2)
% slope of a line
% m = dy / dx
% m = rise / run
dy = computeRise(y1, y2);
dx = computeRun(x1, x2);
m = dy / dx;
end
% local functions
function dy = computeRise(y1, y2)
dy = y2 - y1;
end
function dx = computeRun(x1, x2)
dx = x2 - x1;
end
MATLAB "strings" are unique. Single-quoted text produce character arrays and double-quoted text produce actual strings. These are not the same. There is no recommendation except to be consistent in your usage of single- and double-quoted text.
For print statements with quotations, consider using double-quote to surround the text and single-quotes around the quoted text.
% preferred method
fprintf("This is the 'preferred' way of quoting")
% less preferred
fprintf('This is '''less preferred''')
Use whitespace to increase readability.
Some rules for when to use whitespace:
- Immediately after a comma, semicolon, colon, or operator:
x = 1; y = 1;
z = x + y;
If there are long or multiple operations in a single statement, use spaces sparingly and give whitespace to grouped terms.
% preferred
a = 3;
b = 4;
c = a*a + b*b
a = (b / sin(b)) * sin(A)
% wrong
c = a * a + b * b
a = b / sin(b) * sin(A)
Do not use spaces to align assignments across lines.
% DO NOT DO THIS
a = 1;
b = 3;
hypotenuse = a^2 + b^2
Do not have trailing whitespace, e.g., space after command and before a new line.
Use a space around function inputs and output arguments.
Make comments clear, concise, and full sentences. This includes proper capitalization and punctuation.
Block comments should consists of paragraphs with the above rule.
Use inline comments sparingly. If an inline comment is included, it should be separated with at least 2 spaces from the statement.
% correct
x = x + 1; # my comment
y = x * 3; # also acceptable
% wrong
z = x + y; # bad comment
Write documentation for all non-public or non-nested functions. For non-public or non-nested functions, classes, or modules, a single statement providing information of what it does is sufficient.
% public function definition
function y = foo(x)
% FUNCTION Perform random math on x
%
% Args:
% x (double): Input
%
% Returns:
% y (double): Output of math operation
end
% non-public function
function y = boo(x)
% function takes input x and prints to screen
end
The help section should be placed inside the function, class, or module definition block. The help section should follow the same indentation rules.
There should be one blank line between the help section and the code. The only exception is for small functions or scripts, e.g, less than 5 lines or so, to help distinguish a help section and commented code.
function y = boo(x)
% function takes input x and prints to screen
fprintf('input was %s\n', x)
end
Favor simple help sections over complex or overly wording ones.
- Include a one line description
- (Optional) Long description, if necessary
- List of input arguments with datatype, description, and whether they are optional
- List of output arguments with the same info as inputs
- (Optional) Examples
function [a, b, c] = triangleAngles(x, y, z, varargin)
% TRIANGLEANGLES Compute angle of a triangle
%
% Args:
% x (double): triangle side 1
% y (double): triangle side 2
% z (double): triangle side 3
% degrees (logical): return angle in degrees.
% The default is true.
%
% Returns:
% a (double): angle between side 1 and side 2
% b (double): angle between side 2 and side 3
% c (double): angle between side 1 and side 3
%
% Examples:
% [a, b, c] = triangleAngles(1, 1, sqrt(2))
% outputs a=90, b=45, c=45
%
% [a, b, c] = triangleAngles(3, 4, 5)
% outputs a=90, b=60, c=30
end
Type | Naming convention |
---|---|
Function | camelCase |
Class | PascalCase |
Class Property | camelCase |
Class Method | camelCase |
Package | lowercase |
Variable | camelCase |
Method Argument | camelCase |
Global | UPPERCASE, UPPER_CASE |
Constant | UPPERCASE, UPPER_CASE |
Exception | PascalCase |
Unit Test | camelCase, PascalCase |
There are some exceptions/substitutions that conform to other case(s), e.g., camelCase -> snake_case
Function names should follow the camelCase
convention.
Class names should follow the PascalCase
convention.
Class property names should follow the camelCase
convention.
They should follow the same convention as method arguments.
Class method names should follow the camelCase
convention.
They should follow the same convention as function names.
Package names should follow the lowercase
convention.
Packages names should proceed with +
and use short, abbreviated names, if possible.
Variables names should follow the camelCase
convention.
They should follow the same convention as function names.
Method argument names should follow the camelCase
convention.
They should follow the same convention as variable names.
Global variable names should follow the UPPERCASE
, UPPER_CASE
convention.
Only use underscores when it improves readability.
Constant names should follow the UPPER_CASE
convention.
Underscores should be used to separate words, and generally follow global variable names.
Exception names should follow the PascalCase
convention.
They should follow the same convention as class names.
If the exception is an error, consider using Error
at the end of the name.
Unit test names should follow the camelCase
or PascalCase
convention.
All unit test file names should preceed with 'test'.
Script or function unit test names should follow the same convention as function names.
Class unit test names shold follow the same convention as class names.
Individual test names should, at a minimum, specify if the test result in the name.