MATLAB Language Useful tricks Comment blocks


Example

If you want to comment part of your code, then comment blocks may be useful. Comment block starts with a %{ in a new line and ends with %} in another new line:

a = 10;
b = 3;
%{
c = a*b;
d = a-b;
%}

This allows you fo fold the sections that you commented to make the code more clean and compact.

These blocks are also useful for toggling on/off parts of your code. All you have to do to uncomment the block is add another % before it strats:

a = 10;
b = 3;
%%{ <-- another % over here
c = a*b;
d = a-b;
%}

Sometimes you want to comment out a section of the code, but without affecting its indentation:

for k = 1:a
    b = b*k;
    c = c-b;
    d = d*c;
    disp(b)
end

Usually, when you mark a block of code and press Ctrl+r for commenting it out (by that adding the % automatically to all lines, then when you press later Ctrl+i for auto indentation, the block of code moves from its correct hierarchical place, and moved too much to the right:

for k = 1:a
    b = b*k;
    %     c = c-b;
    %     d = d*c;
    disp(b)
end

A way to solve this is to use comment blocks, so the inner part of the block stays correctly indented:

for k = 1:a
    b = b*k;
    %{
    c = c-b;
    d = d*c;
    %}
    disp(b)
end