MATLAB code style guide

Precedence of rules

  1. When extending existing code, follow the style of that code.
  2. Where there are no existing style rules, use this guide.
  3. If this guide doesn’t cover it, try another guide (Richard Johnson’s, David Schwartz’s).

Variable names

  1. Variables, in general, should be given meaningful and pronounceable names.
  2. 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 as x, y, z.
  3. Acronyms should be treated as a single word for the purpose of casing.
  4. Variable names should be lowerCamelCased, except
  5. 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
  1. Negated boolean names should be avoided.
% Good:
if isFound % ...
% Bad:
if ~isNotFound % ...
  1. The prefix n should be used for variables representing the number of objects (e.g., nItems).

Globals

  1. Variables should only be declared as global if they are expected to be constant.
  2. Usage of globals should be kept to a minimum.

Functions
Names

  1. Function names should be UpperCamelCased, except
  2. Functions based upon a builtin MATLAB function may be lowercased, in the traditional MATLAB style.

Header

  1. All functions (not including nested or subfunctions) should contain an H1 line and help text denoting usage.
  2. 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).
  3. 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

  1. Functions should always include an end statement, even if no subfunctions are present in the same file.
  2. 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

  1. Functions should be used instead of scripts, where appropriate.
  2. Lots of small functions should be used instead of a few big functions.
  3. Packages should be used instead of individual functions, where appropriate.

Syntax
White space

  1. There should be a space before and after all binary operators (=, ==, +, *, &&, etc.), except
  2. The colon operator, :, and the exponentiation operators, ^ and .^.
  3. There should be a space after a comma, but not before.
  4. There should be no white space immediately inside brackets, (), {}, {}.
  5. Extra spacing is permissible if it improves alignment.
  6. Tabs should be made of space characters, not a tab character.
  7. 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

  1. Code should be vectorised, where possible, in preference to loops.
  2. Short loops for code that cannot be vectorised should use cellfun or similar.
  3. Outputs from loops should be initialised before the loop.
  4. switch statements for character values should include an “otherwise” statement.
  5. if, for and while clauses 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

  1. Line lengths should be less than 80 characters. Longer lines should be split at a graceful point (e.g., after a comma or operator).
  2. There should only be one command on any line.

Floating point numbers

  1. Floating point values should always include a digit before the decimal point.
% Good:
0.5
% Bad:
.5    % less readable
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 204 other followers

%d bloggers like this: