Quantcast

Documentation Center

  • Trial Software
  • Product Updates

Add Comments to Programs

This topic explains how and why to add comments to your program files.

When you write code, it is a good practice to add comments that describe the code. Comments allow others to understand your code, and can refresh your memory when you return to it later. Add comments to MATLAB® code using the percent (%) symbol.

Comment lines can appear anywhere in a program file, and you can append comments to the end of a line of code. For example,

% Add up all the vector elements.
y = sum(x)           % Use the sum function.

Comments are also useful for program development and testing—comment out any code that does not need to run. To comment out multiple lines of code, you can use the block comment operators, %{ and %}:

a = magic(3);
%{
sum(a)
diag(a)
sum(diag(a))
%}
sum(diag(fliplr(a)))

The %{ and %} operators must appear alone on the lines that immediately precede and follow the block of help text. Do not include any other text on these lines.

To comment out part of a statement that spans multiple lines, use an ellipses (...) instead of a percent sign. For example,

header = ['Last Name, ',      ...
          'First Name, ',     ...
      ... 'Middle Initial, ', ...
          'Title']

The MATLAB Editor includes tools and context menu items to help you add, remove, or change the format of comments for MATLAB, Java®, and C/C++ code. For example, if you paste lengthy text onto a comment line, such as

% This is a program that has a comment that is a little more than 75 columns wide.
disp('Hello, world')

and then press the button next to Comment on the Editor tab, the Editor wraps the comment:

% This is a program that has a comment that is a little more than 75
% columns wide.
disp('Hello, world')

By default, as you type comments in the Editor, the text wraps when it reaches a column width of 75. To change the column where the comment text wraps, or to disable automatic comment wrapping, adjust the Editor/Debugger Language preference settings labeled Comment formatting.

The Editor does not wrap comments with:

  • Code section titles (comments that begin with %%)

  • Long contiguous strings, such as URLs

  • Bulleted list items (text that begins with * or #) onto the preceding line

Related Examples

More About

Was this topic helpful?