2.4: Documenting Scripts with Comments

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    2.4: Documenting Scripts with Comments

    A script can be correct and still be hard to understand. Good programmers write comments to explain what their code does and why it does it. In MATLAB, a comment begins with the percent symbol %. MATLAB ignores comments when the program runs.

    Example \(\PageIndex{1}\)

    % This program calculates the area of a rectangle.
    % Author: Your Name

    % Assign a value for the width
    width = 4;

    % Assign a value for the height
    height = 3;

    % Calculate the area
    area = width * height;


    This version is easier to read. The semicolons suppress intermediate output, and the comments explain the purpose of each part of the script.

    Block Comments

    For a comment that spans multiple lines, MATLAB also supports block comments using %{ and %}.

    For example, the following comment block can be added to the beginning of the rectangleArea script.

    %{
    This program calculates the area of a rectangle.
    Author: Your Name
    %}

    Help Text

    If the first lines of a script are comments, MATLAB can display them when someone uses the help command. This is very useful because it allows another user, or future you, to quickly understand what the script is for.

    For example the command:

    help rectangleArea

    Will return:

    This program calculates the area of a rectangle.
    Author: Your Name 
    Note

    Best practice: Start every script and function with a short comment block that explains what the file does, what inputs it needs, what outputs it creates, and who wrote it.


    This page titled 2.4: Documenting Scripts with Comments was last modified on Tue, 30 Jun 2026 02:11:44 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.