MATLAB code style guide
Precedence of rules
- When extending existing code, follow the style of that code.
- Where there are no existing style rules, use this guide.
- If this guide doesn’t cover it, try another guide (Richard Johnson’s, David Schwartz’s).
Variable names
- Variables, in general, should be given meaningful and pronounceable names.
- Index variables with short scope may be given short names, e.g.,
i,j,k. Likewise, mathematical variables with short scope may be given an appropriate short name such asx,y,z. - Acronyms should be treated as a single word for the purpose of casing.
- Variable names should be
lowerCamelCased, except - Variables representing constants should be
UPPER_UNDER_CASED.
% Good: meanHeight = mean(height); PI_SQUARED = pi^2; % Bad: foo = 1:10; % not meaningful firstdayofweek = 'Monday'; % wrong case uRL = '4dpiecharts.com'; % treat acronym as word
- Negated boolean names should be avoided.
% Good: if isFound % ... % Bad: if ~isNotFound % ...
- The prefix
nshould be used for variables representing the number of objects (e.g.,nItems).
Globals
- Variables should only be declared as global if they are expected to be constant.
- Usage of globals should be kept to a minimum.
Functions
Names
- Function names should be
UpperCamelCased, except - Functions based upon a builtin MATLAB function may be
lowercased, in the traditional MATLAB style.
Header
- All functions (not including nested or subfunctions) should contain an H1 line and help text denoting usage.
- If appropriate, the preamble can contain Examples and See Also sections, details of toolbox dependencies and details of side effects (e.g., creating a plot).
- The author, date last modifed and copyright should also be included near the top of the function, after a blank line, after the header comments. (The blank line is so that this does not appear in the function’s help text.)
Content
- Functions should always include an end statement, even if no subfunctions are present in the same file.
- Where appropriate, functions should include %#ok tags to avoid m-lint warnings.
% Good:
function area = CalculateAreaOfRectangle(width, height)
% AREA = CALCULATEAREAOFRECTANGLE(HEIGHT, WIDTH) calculates the area of a rectangle.
% HEIGHT and WIDTH should be nonnegative numeric values.
% Where they are vectors, AREA is the pointwise product.
% $Author: rcotton $ $Date: 2011/02/17 $ $Revision: 1.1 $
% Copyright: 4dpiecharts.com 2011
validateattributes(height, {'numeric'}, {'nonnegative'}, ...
'CalculateAreaOfRectangle', 'height');
validateattributes(width, {'numeric'}, {'nonnegative'}, ...
'CalculateAreaOfRectangle', 'width');
area = width .* height;
end
Code Reuse
- Functions should be used instead of scripts, where appropriate.
- Lots of small functions should be used instead of a few big functions.
- Packages should be used instead of individual functions, where appropriate.
Syntax
White space
- There should be a space before and after all binary operators (
=,==,+,*,&&, etc.), except - The colon operator, :, and the exponentiation operators,
^and.^. - There should be a space after a comma, but not before.
- There should be no white space immediately inside brackets,
(),{},{}. - Extra spacing is permissible if it improves alignment.
- Tabs should be made of space characters, not a tab character.
- Tabs should be 3 spaces wide.
% Good: y = x + 1; z = m(1:2, 1:4); [1.23 4.56; ... 7 8] % extra spaces align decimal points % Bad: y=x+1; % no spaces z = m( 1:2,: ); % spaces inside brackets, none after comma
Loops
- Code should be vectorised, where possible, in preference to loops.
- Short loops for code that cannot be vectorised should use
cellfunor similar. - Outputs from loops should be initialised before the loop.
switchstatements for character values should include an “otherwise” statement.if,forandwhileclauses should not be bracketed.
% Good:
mean(height) % mean is vectorised
cellfun(@mean, {1:3, 4:6, 7:9}) % cellfun type functions are the next best thing
% Bad:
total = 0;
count = 0;
for i = 1:length(height)
total = total + height(i);
count = count + 1;
end
meanHeight = total / count;
% Slower and vastly more effort than it should be
Lines
- Line lengths should be less than 80 characters. Longer lines should be split at a graceful point (e.g., after a comma or operator).
- There should only be one command on any line.
Floating point numbers
- Floating point values should always include a digit before the decimal point.
% Good: 0.5 % Bad: .5 % less readable
