Loren on the Art of MATLAB

August 30th, 2006

Commenting Code

My thesis advisor wanted to cheerfully annihilate me one day many years ago when he was working with a program I wrote. I had a huge set of comments describing the program inputs and outputs, and all the ins and outs of using the program I could think of. Unfortunately for him, the final comment read like this:

   "Ignore all previous comments; they were for an earlier version of this program."

I have tried to be a better comment citizen ever since.

Contents

When to Comment

Here are some of my guidelines for when to insert comments. Note: I don't always follow my own advice!

Help

  • The H1 line -- the first help line in an M-file, following the function declaration, if the M-file is not a script.
  • The help body -- the first block of comments in the M-file, contiguous to the H1 line, stating the syntax and usage. This section may contain sections for Limitations, Examples, Class support, and See also references.

Functions

  • An H1 line for each subfunction. I don't, however, necessarily feel the same way about nested functions, depending on their usage. What do you think?
  • The final end statement of each function, if used, and certainly when nested functions are in the file.
  • In nested functions, when a variable is likely to be changed from code elsewhere in the file. This way, I am more likely to understand what I'm seeing when I debug.

Algorithms

  • A description of each logical chunk of code, especially when an algorithm has many steps.
  • Equivalent M-code or perhaps code in some other language, especially if some code is potentially very obscure or dense. An example might be to show the explicit for-loop equivalent code versus the vectorized expression.

Comment Tip

Block comments can be very useful for placing comments in the middle of a multi-line statement or expression in MATLAB. Sometimes I end up with a long list of properties I think I want to change in plot.

type hgComments
hgComments
% Base script to illustrate block comments.

t = pi:pi/20:5*pi;
sinc = sin(30*t)./t;
h = plot(t,sinc);
set(h,...
    'linestyle','--',...
    'color','m',...
    'marker','diamond',...
    'markersize',8,...
    'markerfacecolor','c',...
    'markeredgecolor','b'...
    )
    

If I try to just comment out the line setting the MarkerFaceColor property, I find that the editor shows me an mlint message.

dbtype hgCommentsBad
1     % Script to illustrate misuse of comments within a statement.
2     
3     t = pi:pi/20:5*pi;
4     sinc = sin(30*t)./t;
5     h = plot(t,sinc)
6     set(h,...
7         'linestyle','--',...
8         'color','m',...
9         'marker','diamond',...
10        'markersize',8,...
11    %    'markerfacecolor','c',...
12        'markeredgecolor','b'...
13        )
14        
info = mlint('hgCommentsBad');
info.message
ans =
Terminate statement with semicolon to suppress output.
ans =
There may be a parenthesis imbalance around here.
ans =
Terminate statement with semicolon to suppress output.
ans =
There may be a parenthesis imbalance around here.
try
    hgCommentsBad
catch
    l = lasterror();
    disp(l.message)
end
Error: File: H:\Documents\LOREN\MyJob\Art of MATLAB\hgCommentsBad.m Line: 11 Column: 31
Expression or statement is incorrect--possibly unbalanced (, {, or [.

Instead I can use block comments to achieve the goal of not setting the property in the middle of my list, without deleting the code, until I am sure that's the change I want.

dbtype hgCommentsGood
1     % Script to illustrate block comments.
2     
3     t = pi:pi/20:5*pi;
4     sinc = sin(30*t)./t;
5     h = plot(t,sinc);
6     set(h,...
7         'linestyle','--',...
8         'color','m',...
9         'marker','diamond',...
10        'markersize',8,...
11    %{
12        'markerfacecolor','c',...
13    %}
14        'markeredgecolor','b'...
15        )
16        
info = mlint('hgCommentsGood');
info.message
hgCommentsGood

Can you see yourself using block comments to help you with some of your programming tasks? Let me know.


Published with MATLAB® 7.3

13 Responses to “Commenting Code”

  1. StephenL.CSSM replied on :

    Great column.

    A few comments about commenting:

    1. I never use block comments since most tools & editors outside of the native editor in MATLAB don’t syntax highlight them right. That includes: vim, highlite, etc… Many times I need to get my code color coded and exported to html and the tools that are available for that don’t support them. That is why I wish the publishing function in matlab accepted functions as input and just exported them synatx highlighted. This would be very useful.

    2. The todo/fixme report is my best friend in MATLAB. I customized it a bit since desktop space is at a premium and MATLAB doesn’t support multiple desktops. I keep the todo/fixme report open at all times since I tend to work on very large projects and having all that buried in the comments is very useful. If I didn’t have that report I would have to write my own. My boss was very impressed with that tool when I demoed it to our team.

    3. I tend to only comment the why’s since the how’s are right their in the code except for really complicated code.

    4. For longer functions, I usually write out the steps in a list format at the top of the function with each step numbered. In the code, that same comment with step number starts that section. I have been complimented several times for doing that.

    5. I religiously put see also’s in my code so when i type help they show up as links I can click on.

    6. I end every function with “end % functionName ” This way if I ever have to copy a function into another function, I easily can tell where one begins and one ends.

    I hope these are useful for others.

    Stephen

  2. Sia replied on :

    I think many new languages including Matlab are considered as self explanatory programming languages and the code itself is the comment; however we all well comment our code, but is seems the need to put comments in the code (the way it was in FORTRAN) is decreasing

    I never put a comment inside the parameters of the functions I think it causes the code to lose her beauty; instead I rewrite the whole function header inside a new comment block (or just copy and past it) and put a note describing the differences

    And I have a question too:
    In C# and some other languages there is a new XML commenting that helps you compile your comments into a help file (like a .chm in windows) It becomes very handy when we work with different classes and functions, I was wondering if there is such a tool in Matlab, maybe you should push Mathworks to put it in the next generation of matlab

    And another question how do you control and balance the time you comment your code, I mean sometimes we make some comment that is not only a waste of time but also a damage to the readability of the code (some excess comments make the code really ugly) . I was wondering how your team (as professionals) manages the documentation phase time

    Thanks

  3. John D'Errico replied on :

    Good code should be self documented, i.e.,

    - Use relatively short lines.
    - Use meaningful variable names. Long names are not bad if they are descriptive.
    - Where a project uses your own functions, make those names nicely descriptive and readable.

    Good code should have internal comments. There is NO beauty in undocumented code. Each functional block should have a comment that explains what is done. Don’t expect someone (who will take over your code when you unexpectedly get hit by the crosstown bus, or just retire) to understand what your code does and how it works with no comments! They will NOT appreciate its beauty and subtlety. They WILL rain down curses on your name as they try to read your “beautiful” code.

    These comments are purely my own opinion of course. But they are the comments of someone who has written thousands of matlab functions and well over a dozen complete toolboxes. I am someone who has had to return to my own code, years after it was written, and try to repair it when something unexpected happens. If you don’t care about that person who must take over your code, at least care about yourself!

    John

  4. Lars Barring replied on :

    Loren,
    This is a rare situation when I feel that your examples does not do what they are intended to — to give a lucid example of some language feature or programming tip.

    Way back I was facing exactly the same situation, I had a very long list of handle graphics properties in a multi-line staement that I wanted to experiment with. And I immediately tried the most obvious way, to put a % first on the relevant rows. And as you show, it did not work.

    Turning to CSSM for help I got the advice to use … (i.e. the line continuation indicator) first in the line as everything after would be ignored, or taken as a comment if you like. While three characters are not optimal, I find it much more elegant than block comments. But I would have liked the % to work.

    Having to use block comments (i.e. adding/removing a line before and another line after) for each of several non-consecutive lines in a long multi-line hg statement just to experiment does not seem to be a particularly easy approach, and I doubt that the code would be very readable.

    Lars

  5. Ofek Shilon replied on :

    Thanks for (yet another) great column.
    One additional personal liking: i tend to comment end’s not only of functions, but of lengthy flow-controls as well: if’s, switch’s, and while’s. eg:

    if iscond
    blah;
    .
    .
    .
    blahblah;
    else % ~iscond
    yadda;
    .
    .
    .
    yaddayadda;
    end %iscond

    Ofek

  6. lehalle replied on :

    I use OCAMAWEB to comment my code for many years now.

    The Ocamaweb blocks have some interesting properties that the “common” matlab blocks do not have:
    - they can be closed (you can choose to open a block by %%, then it’s like a matlab block, or you can open a block by %)
    - more than one level of sectionning is available
    - you can use some real LaTeX codes (i.e. LaTeX into a line)

    http://sourceforge.net/project/showfiles.php?group_id=66639

  7. lehalle replied on :

    sorry for the typo of my previous post:
    “you can choose to open a block by %%, then it’s like a matlab block, or you can open a block by %< and close it by %>”

  8. Oliver A. Chapman, PE replied on :

    Loren,

    Could you explain your term, “block comments?” The link in your article appears to be broken and I haven’t been able to figure out if it is a type of MatLab command, MatLab editor command or just a general term applying to a style of comments. I did find a reference to the term on the MathWorks web site, but that is broken also. It appeared to refer to a section of MatLab documentation:

    Adding Comments :: Editing and Debugging M-Files(Desktop Tools and Development Environment)

    But, I can’t find that by surfing thru the documentation contents.

  9. Loren replied on :

    Oliver-

    I fixed the link. It broke with the release of R2006b. Thanks for catching it.

    Block comments are delimiters around a block (of anything you want to be in comments). They start with a line like this:

    %{

    and end with a line like this

    %}

    See lines 11 and 13 in the last code block in the blog.

    Using them, you don’t need to have % in front of every line in between, sometimes rendering the comment more readable. In the case of comment embedded in a code that continues on multiple lines, block comments also render the remaining code usable.

    –Loren

  10. Oliver A. Chapman, PE replied on :

    Loren,

    Thanks, now I understand what these “block comments” are. I can see how they might be used with prototype code: e.g., you can disable a section of code and observe the behavior of the rest when you execute it.

    However, I can’t see how I would use it. There is a risk that I will visually miss the section that is commented out. Using the “%” at the beginning of each line in the block makes the commented section visually prominent. Since the MatLab editor has the feature to automate the adding of the “%” to the selected lines, why use this “riskier” technique?

    I see that the MatLab editor will color code both techniques to aid in the visual prominence, so I suppose the risk of missing the comments is low.

    I understand that a similar feature is available in C, so likely The MathWorks has received requests for this feature from their customers and it is always good to accommodate your customers.

    But, for final code, I want the comments to really stand out as visually separate from the commands, so I’ll continue to use “%” on each line.

    Sorry I missed you in Seattle today. I wanted to attend your seminar, but schedule issues prevented it.

  11. Memming replied on :

    Here’s how to enable syntax coloring in Vim.
    http://blog.memming.com/entry/block-commenting-in-MATLAB-and-syntax-highlighting-in-vim

  12. Ron replied on :

    FYI, the block comment link seems to be broken again. In my case, I’m using block comments to disable a section of a long m-file function to see how much faster it will run. The current function takes 8 hrs to run on a fast machine.

  13. Loren replied on :

    Ron-

    Sorry for the broken link. Here is the link for block comments:

    http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/f2-53314.html#f2-53527

    –Loren

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Jun: I totally can not believe it, Loren. You are really helpful. Thank you so much, MATLAB master!
  • Loren: Wow folks- Always lots of interest when there’s a quickie to try out! I will only make 2 general...
  • Loren: Jun- ismember is your friend here: >> [aa,ind] = ismember(Array2,Arra y1) aa = 1 1 1 1 1 1 1 ind = 1 2 1 4 4 3...
  • Dan: I like the first way better than the second way. Combining the arrays into one and running any is nice, although...
  • James Myatt: How about I = (a == 0 | b == 0); a(I) = []; b(I) = [];
  • Tunc: Hello Loren, love your blog because of such inspiring and challenging comments to such ’small’...
  • Pekka Kumpulainen: Here is my tradeoff. I usually want to keep the original variables as they are most probably...
  • Iain: Followup: Of course, to allow NaNs (counting them as non-zero): mask = (a~=0) & (b~=0); The mask says “a...
  • Matt Fig: I would usually go with something like this: y = a&b; x = a(y); y = b(y); But I was surprised to find...
  • kk: c=all([a;b]) a(c) a(b)

These postings are the author's and don't necessarily represent the opinions of The MathWorks.