Skip to main content
Engineering LibreTexts

6.2: if Statement

  • Page ID
    86200
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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 is shared under a CC BY-NC-SA 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; a detailed edit history is available upon request.