MATLAB Language Useful tricks Comment blocks

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any MATLAB Language Question?