-Techniques and tricks‎ > ‎Matlab‎ > ‎

Coding punctuation

There are many acceptable ways of punctuating Matlab code in a .m (dot-m) file. Some people ask Steve why he uses the punctuation that he does. Here is the explanation. 

Consider the following simple for-loop:

mylist = [ 1 2 3 4 5 ];
for i=1:numel(mylist),          % note the comma after the for statement
   mylist(i) = mylist(i) * 2;   
   i,                           % note the comma after the i
end;                            % note the semicolon after the 'end'

In a file or in pasted text, this code fragment can also be punctuated:

mylist = [ 1 2 3 4 5 ];
for i=1:numel(mylist)
   mylist(i) = mylist(i) * 2;

Why does Steve generally write using the first approach? The reason is that the code will run the same way if it is reduced to a single line:

mylist = [1 2 3 4 5]; for i=1:numel(mylist), mylist(i) = mylist(i) * 2; i, end;   % this will run

mylist = [1 2 3 4 5]; for i=1:numel(mylist) mylist(i) = mylist(i) * 2; i end      % this will not run

Usually this is not important, but it allows the formatting to be invariant if the code is collapsed onto a single line or written out. So Steve's punctuation approach is to
  1. End every conditional branch expression (such as for or while) with a comma
  2. End every statement with either a semicolon (if the output is to be suppressed) or a comma (if the output is to be written to the command line)
  3. End every end with a semicolon (note that classdef objects cannot end with a ';' for some reason).