6.2: if Statement

Physical Modeling in MATLAB · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

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

    6.2: if Statement

    Now suppose that when we find a Pythagorean triple we want to display a message. The if statement allows you to check for certain conditions and execute statements if the conditions are met. For example:

    if a^2 + b^2 == c^2
        disp("Yes, that is a Pythagorean triple.")
    end

    The syntax is similar to a for loop. The first line specifies the condition we’re interested in. If the condition is true, MATLAB executes the body of the statement, which is the indented sequence of statements between the if and the end.

    MATLAB doesn’t require you to indent the body of an if statement, but it makes your code more readable, so you should do it.

    If the condition is not satisfied, the statements in the body are not .

    Sometimes there are alternative statements to execute when the condition is false. In that case, you can extend the if statement with an else clause.

    The complete version of the previous example might look like this:

    if a^2 + b^2 == c^2
        disp("Yes, that is a Pythagorean triple.")
    else
        disp("No, that is not a Pythagorean triple.")
    end

    Statements like if and for that contain other statements are called compound statements. All compound statements finish with end.


    This page titled 6.2: if Statement was last modified on Thu, 17 Nov 2022 18:18:52 GMT and is shared under a CC BY-NC 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.