5.6: Multiple Branches with if-elseif-else

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.

    5.6: Multiple Branches with if-elseif-else

    Sometimes a program has more than two possible paths. In that case, we can use if, elseif, and else. MATLAB checks the conditions from top to bottom. As soon as one condition is true, MATLAB runs that block and skips the remaining branches.

    if condition1
    action1
    elseif condition2
    action2
    elseif condition3
    action3
    else
    action4
    end

    The final else is optional, but it is useful because it handles any case that was not caught earlier.

    Example: Piecewise Functions

    Branches are commonly used to define piecewise mathematical functions. A piecewise function uses a different formula depending on the value of the input. For example, suppose we define y as follows:

    y = x^2       when x < 0
    y = 2*x + 1   when 0 <= x < 5
    y = 2*x + 2   when 5 <= x <= 10
    y = 100       when x > 10

    In MATLAB, this can be written as a function using if-elseif-else.

    function y = findY(x)
    % findY evaluates a piecewise function.
    
    if x < 0
        y = x^2;
    elseif x >= 0 && x < 5
        y = 2*x + 1;
    elseif x >= 5 && x <= 10
        y = 2*x + 2
    else
        y = 100;
    end
    end

    The following is another version of the same function. In the first elseif condition, x < 5 has replaced x >= 0 && x < 5 because the conditions are checked in order. If the first condition is not true, then MATLAB already knows that x is not less than 0. Therefore, x must be greater than or equal to 0, so there is no need to check x >= 0 again. This version is easier to read.

    function y = findY(x)
    % findY evaluates a piecewise function.
    
    if x < 0
        y = x^2;
    elseif  x < 5
        y = 2*x + 1;
    elseif  x <= 10
        y = 2*x + 2
    else
        y = 100;
    end
    end
    Note

    Why Order Matters
    The order of conditions matters. MATLAB only executes the first true branch. For example, in the above function, notice the error if we swap the first two conditions x < 0 and x < 5.


    This page titled 5.6: Multiple Branches with if-elseif-else was last modified on Tue, 30 Jun 2026 02:11:52 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.