MatlabStyle2 Book PDF
MatlabStyle2 Book PDF
Guidelines 2.0
Richard Johnson
MATLAB Style Guidelines
ISBN
Library of Congress Control Number
2
Contents
Introduction 5
Naming Conventions 7
Variables 7
Constants 13
Structures 14
Functions 15
General 19
Statements 21
Variables and constants 21
Globals 21
Loops 22
Conditionals 23
General 24
Layout, Comments and Documentation 29
Layout 29
White Space 30
Comments 32
Files and Organization 37
M Files 37
Input and Output 39
Toolboxes 40
Style quotes 41
References 43
3
MATLAB Style Guidelines
4
Introduction
Advice on writing MATLAB code usually addresses efficiency
concerns, with recommendations such as “Don’t use loops.” This
document is different. Its concerns are correctness, clarity and
generality. The goal of these guidelines is to help produce code
that is more likely to be correct, understandable, sharable and
maintainable.
Some ways of coding are better than others. It’s as simple as that.
Coding conventions add value by helping to make mistakes
obvious. As Brian Kernighan writes, “Well-written programs are
better than badly-written ones -- they have fewer errors and are
easier to debug and to modify -- so it is important to think about
style from the beginning.”
When people look at your code, will they see what you are
doing? The spirit of this book can be pithily expressed as “Avoid
write-only code.”
This document lists MATLAB coding recommendations
consistent with best practices in the software development
community. These guidelines are generally the same as those for
C, C++ and Java, with modifications for MATLAB features and
history. The recommendations are based on guidelines for other
languages collected from a number of sources and on personal
experience. These guidelines are written with MATLAB in mind,
and they should also be useful for related languages such as
Octave, Scilab and O-Matrix.
Issues of style are becoming increasingly important as the
MATLAB language changes and its use becomes more
widespread. In the early versions, all variables were double
precision matrices; now many data types are available. Usage
has grown from small scale prototype code to large and complex
5
MATLAB Style Guidelines
production code developed by groups. Integration with Java is
standard and Java classes can appear in MATLAB code. All of
these changes have made clear code writing more important and
more challenging.
Guidelines are not commandments. Their goal is simply to help
programmers write well. Many organizations will have reasons
to deviate from some of these guidelines, but most organizations
will benefit from adopting some style guidelines.
6
Naming Conventions
The purpose of a software naming convention is to help the
reader and the programmer. Establishing a naming convention
for a group of developers is very important, but the process can
become ridiculously contentious. There is no naming convention
that will please everyone.
Following a convention is more important than what the details
of the convention are. This section describes a commonly used
convention that will be familiar to many programmers of
MATLAB and other languages.
Variables
The names of variables should document their meaning or use.
MATLAB can cope with
z = x * y
8
Naming Conventions
This notation is taken from mathematics where it is an
established convention for indicating the number of objects.
nFiles, nSegments
mRows
thisPoint
tableNo, employeeNo
iTable, iEmployee
~isNotFound
Use
isFound and ~isFound
Avoid
isNotFound
Use
html, isUsaSpecific, checkTiffFormat()
Avoid
hTML, isUSASpecific, checkTIFFFormat()
Use
roi, or regionOfInterest
Avoid
imageRegionForAnalysis
12
Naming Conventions
when they are strings of contractions. A bigger problem occurs if
a prefix, as is often suggested, encodes data type. Then if the
type needs to be changed, all incidences of the variable name
need to be changed.
Use
thetaDegrees
Avoid
uint8thetaDegrees
Constants
The MATLAB language does not have true constants (except as
constant properties in objects). Use standard practices to name
and define constants so that they can be recognized and not
unintentionally redefined.
MAX_ITERATIONS, COLOR_RED
13
MATLAB Style Guidelines
This practice is used by The MathWorks. For example the
constant pi is actually a function.
offset, standardValue
Structures
Structure names should begin with a capital
letter.
This usage is consistent with other languages, and it helps to
distinguish between structures and ordinary variables.
Use
Segment.length
Avoid
Segment.segmentLength
14
Naming Conventions
fieldnames are not consistent, for example, when a structure has
field
Acme.source = ‘CNN’;
Acme.sourceName = ‘Bloomberg’;
Functions
The names of functions should document their use.
linspace, meshgrid
isequalwithequalnans
predictSeaLevel, publishHelpPages
15
MATLAB Style Guidelines
Some programmers prefer to use underscores in function
names, but this practice is not common.
Use
computeTotalWidth
Avoid
compwid
max, gcd
mean, standardError
16
Naming Conventions
This practice increases readability, making it clear what the
function should (and possibly should not) do. This makes it
easier to keep the code clean of unintended side effects.
plot
getobj, setAppData
computeWeightedAverage, computeSpread
findOldestRecord, findTallestMan
17
MATLAB Style Guidelines
Consider using the prefix initialize where an
object or a variable is established.
The American initialize should be preferred over the British
initialise. Avoid the abbreviation init.
initializeProblemState
isOverpriced, iscomplete
18
Naming Conventions
the possibility of unexpected behavior or error. Names can be
checked for shadowing using which -all or exist.
Overload functions will of course have the same name. Do not
create an overload situation when a polymorphic function
would be adequate.
General
Consider a unit suffix for dimensioned variables
and constants.
Using a single set of units for a project is an attractive idea that
is only rarely implemented completely. Adding unit suffixes
helps to avoid the almost inevitable unintended mixed unit
expressions.
incidentAngleRadians
Use
computeArrivalTime
Avoid
comparr
html, cpu, cm
19
MATLAB Style Guidelines
Consider making names pronounceable.
Names that are at least somewhat pronounceable are easier to
read and remember.
20
Statements
Globals
Minimize use of global constants.
Use an m-file or mat file to define global constants. This practice
makes it clear where the constants are defined and discourages
unintentional redefinition. If the m-file access overhead produces
an execution speed problem, consider using a function handle.
Loops
Initialize loop result variables immediately before
the loop.
Initializing these variables improves loop speed and helps
prevent bogus values if the loop does not execute for all possible
indices. This initialization is sometimes called pre-allocation.
Placing the initialization just before the loop makes it easier to see
that the variables are initialized. This practice also makes it easier
to copy all the relevant code for use elsewhere.
result = nan(nEntries,1);
for index = 1:nEntries
result(index) = foo(index);
end
22
Statements
Conditionals
Avoid complex conditional expressions. Introduce
temporary logical variables instead.
By assigning logical variables to expressions, the program gets
automatic documentation. The construction will be easier to read
and to debug.
if (value>=lowerLimit)&(value<=upperLimit)&~…
ismember(value,… valueArray)
:
end
should be replaced by:
fid = fopen(fileName);
if (fid~=-1)
:
else
:
end
23
MATLAB Style Guidelines
Avoid the conditional expression if 0.
Make sure that this usage does not obscure the normal path of
execution. To temporarily bypass code execution, use the block
comment feature of the editor instead of this expression.
switch (condition)
case ABC
statements;
case DEF
statements;
otherwise
statements;
end
General
Avoid cryptic code.
There is a tendency among some programmers, perhaps inspired
by Shakespeare’s line: “Brevity is the soul of wit”, to write
MATLAB code that is terse and even obscure. Writing concise
24
Statements
code can be a way to explore the features of the language.
However, in almost every circumstance, clarity should be the goal.
As Steve Lord of MathWorks has written, “A month from now, if I
look at this code, will I understand what it’s doing?”
Use parentheses.
MATLAB has documented rules for operator precedence, but
who wants to remember the details? If there might be any doubt,
use parentheses to clarify expressions. They are particularly
helpful for extended logical expressions.
Use
THRESHOLD = 0.5;
Avoid
THRESHOLD = .5;
25
MATLAB Style Guidelines
shortSide = 3;
longSide = 5;
otherSide = 4;
longSide^2 == (shortSide^2 + otherSide^2)
ans =
1
But
scaleFactor = 0.01;
(scaleFactor*longSide)^2 ==
((scaleFactor*shortSide)^2 + …
(scaleFactor*otherSide)^2)
ans =
0
Use
iSample>=maxSamples;
Avoid
~(iSample<maxSamples);
26
Statements
useful tool for protection against error conditions is the try
catch construction with MException.
Another line of defense is to use properly ordered expressions in
if statements so that evaluation short circuiting can avoid
evaluation of expressions that will trigger an error.
27
MATLAB Style Guidelines
28
Layout, Comments and
Documentation
Layout
The purpose of layout is to help the reader understand the code.
Indentation is particularly helpful for revealing structure.
totalSum = a + b + c + …
d + e;
function (param1, param2,…
param3)
setText ([‘Long line split’ …
‘into two parts.’]);
Indent 3 or 4 spaces.
Good indentation is probably the single best way to reveal
program structure.
MATLAB Style Guidelines
Indentation of 1 space is too small to emphasize the logical
layout of the code. Indentation of 2 spaces is sometimes suggested
to reduce the number of line breaks required to stay within 80
columns for nested statements, but MATLAB is usually not
deeply nested. Indentation larger than 4 can make nested code
difficult to read since it increases the chance that the lines must be
split. Indentation of 4 is the current default in the MATLAB editor.
White Space
White space enhances readability by making the individual
components of statements stand out.
30
Using space around the assignment character provides a strong
visual cue separating the left and right hand sides of a statement.
Using space around the binary logical operators can clarify
complicated expressions.
simpleSum = firstTerm+secondTerm;
foo(alpha,beta,gamma)
31
MATLAB Style Guidelines
This practice helps to distinguish keywords from function
names.
Comments
The purpose of comments is to add information to the code.
Typical uses for comments are to explain usage, to express the
purpose of the code, to provide reference information, to justify
decisions, to describe limitations, to mention needed
improvements. Experience indicates that it is better to write
comments at the same time as the code rather than to intend to
add comments later.
32
There should be a space between the % and the comment text.
Comments should usually start with an upper case letter and end
with a period.
Header comments
The header comments are the first contiguous block of
comments in an m-file. Write them to provide the user with the
necessary information to use the file.
There are two styles of header comments for functions in
common use. The traditional style has the comments below the
function line and uses only single % signs. It was originally
designed for use in the Command Window.
A more modern style has the comments above the function line.
It often uses MATLAB markup and is designed to produce an
HTML file for the Help and Function Browsers.
33
MATLAB Style Guidelines
Side effects are actions of a function other than assignment of the
output variables. A common example is plot generation.
Descriptions of these side effects should be included in the header
comments so that they appear in the help printout.
Inline comments
Comments in the code as opposed to the header are intended for
a programmer, not a user.
35
MATLAB Style Guidelines
36
Files and Organization
Structuring code, both among and within files is essential to
making it understandable. Thoughtful partitioning and ordering
increase the value of the code.
M Files
Modularize.
The best way to write a big program is to assemble it from well-
designed small pieces (usually functions). This approach enhances
readability, understanding and testing by reducing the amount of
text which must be read to see what the code is doing.
Code longer than two editor screens is a candidate for
partitioning. Keeping related information together on the same
editor screen lets you see certain types of problems and fix them
right away. Small well designed functions are more likely to be
usable in other applications.
Partitioning
All subfunctions and many functions should do one thing very
well. Every function should hide something.
Subfunctions
A function used by only one other function should be packaged
as its subfunction in the same file. This makes the code easier to
understand and maintain.
MATLAB allows accessing a subfunction from outside its m-file.
This is generally a bad idea.
38
Files and Organization
Test scripts
Write a test script for every function. This practice will improve
the quality of the initial version of the function and the reliability
of changed versions. Consider that any function too difficult to
test is probably too difficult to write. Boris Beizer: “More than the
act of testing, the act of designing tests is one of the best bug
preventers known.”
39
MATLAB Style Guidelines
Toolboxes
Organize m-files that have some generality in toolboxes. Check
the function names for shadowing. Add the toolbox locations to
the MATLAB path.
Typically it is useful to have both project and general purpose
toolboxes.
40
Style quotes
Martin Fowler: “Any fool can write code that a computer can
understand. Good programmers write code that humans can
understand.”
“You got to know the rules before you can break ‘em. Otherwise
it’s no fun.” Sonny Crockett in Miami Vice
Plato, “Nothing has its name by nature, but only by usage and
custom.”
References
The Elements of MATLAB Style, Richard Johnson
43