- use parentheses around “if” conditions
good:
if (x = y && (x + y > 3))
not good:
if x = y && (x + y > 3)
- initialize variables and don’t assume zeros
good:
x = 0;
if (a > 0)
x = 1;
end
% at this point x is either 0 or 1
not good:
if (a > 0)
x = 1;
end
% at this point x is either 0 or 1
- matlab variables don’t have scope, create artificial scope for them and don’t reuse them
good:
% this is not needed, but indicate the “scope” of “some_variable”
some_variable = 0
for i = 1 : 100
if (x > 0)
some_variable = 10;
else
some_variable = 0;
end %if
end %for sample
…
for i = 1 : 100
if (some_variable == 10)
…
end %if
end %for i
not good:
some_variable = 0
for i = 1 : 100
if (x > 0)
some_variable = 10;
else
some_variable = 0;
end %if
end %for sample
…
for i = 1 : 100
if (some_variable == 10)
…
end %if
end %for i
- don’t create arrays just to perform matrix operations on them (although this is the preferred way of doing that in matlab):
good:
for sample = 1 : 100
sum_x = sum_x + rand();
end
avg_x = sum_x/100;
not good:
for sample = 1 : 100
x(sample) = rand();
end
avg_x = mean(x);
- use assert when things must not happen (this finds lots of programming bugs and help understand the software). Also, try to make sure there is always an “else” section to an if..elseif statement:
% f() should not return negatives
x = f();
if (x == 0)
do_something
elseif (x > 0)
do_something_else
else
assert(0);
end
- don’t optimize using copy&paste. use functions instead
good:
function f(is_x_positive)
…
% 100 lines of code + some logic on is_x_zero
end
…
if (x == 0)
f(1);
else
f(0);
end % if
not good:
if (x == 0)
…
% 100 lines of code
else
…
% very similar 100 lines of code
end % if
-
don’t use very long lines, use “...” instead (works for both matlab and octave). Putting comments is different lines than code also help with that
-
make sure indentation is correct, not too much, not too little
good:
if (x == 0)
do_something
not good:
if (x == 0)
Do_something
- (you already do this) indicate which statement the “end” ends:
for sample = 1 : 100
if (x > 0)
…
end %if
end %for sample
- extra parentheses around “^” (power) operator
good:
x = x + (y^(z+1));
not good:
x = x + y^(z+1);
- named indexes. use “constants” instead of numbers:
good:
MARRIED = 3;
...
prob_of_emp = women(idx, MARRIED);
not good:
prob_of_emp = women(idx, 3);
- C/matlab style arrays: matlab start from one, C start from zero. try to be consistent with these. when not possible, use another variables and comments. for example:
good:
for interval = 1 : 100
% the first interval start at t=0
t = interval - 1;
x = f(t);
y(interval) = x;
end
not good:
for t = 0 : 100
x = f(t);
y(t+1) = x;
end
- variable names and “constants”: matlab does not have “constants”, so try to use: UPPER_CASE for constants and lower_case for non-constants