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 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?”

Try to avoid the situation described by the Captain in Cool Hand Luke, “What we’ve got here is failure to communicate.”

The importance of this issue is underlined by many authors. Martin Fowler: “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” Kreitzberg and Shneiderman: “Programming can be fun, so can cryptography; however they should not be combined.”

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.

The use of numbers in expressions should be minimized; numbers that are subject to change usually should be named constants instead

If a number does not have an obvious meaning by itself, readability is enhanced by introducing a named constant instead. It can be much easier to change the definition of a constant than to find and change all of the relevant occurrences of a literal number in a file.

Floating point constants should always be written with a digit before the decimal point

This adheres to mathematical conventions for syntax. Also, 0.5 is more readable than .5; it is not likely to be read as the integer 5.

Floating point comparisons should be made with caution

Binary representation can cause trouble, as seen in this example.

shortSide = 3;
longSide = 5;
otherSide = 4;
longSide^2 == (shortSide^2 + otherSide^2)
ans =
     1
scaleFactor = 0.01;
(scaleFactor*longSide)^2 == ((scaleFactor*shortSide)^2 + (scaleFactor*otherSide)^2)
ans =
     0