7.2: 'if' and 'switch' commands

An Introduction to Matlab and Mathcad · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

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

    7.2: 'if' and 'switch' commands

    We discuss the constructs if\elseif\else and switch\case\otherwise in this section.

    Suppose we want to have part of our program run only under certain conditions. For this, we use an if\else structure. The basic format of this structure is:

    if (put condition(s) here)(put calculations here to be run if the conditions are met)
    elseif (other condition(s))(calculations that will run under the new conditions)(more elseif statements, if desired)
    else (calculations run if none of the previous conditions are met)
    end

    Example 7.3.1: Using if

    Let’s write a script M-file that lets a user input a number and then displays if that number is less than 5, between 5 and 10 (inclusive), or greater than 10.

    number = input('Input a number ');
    if number < 5
    disp('Your number is less than 5.')
    elseif number >=5 && number <= 10
    disp('Your number is between 5 and 10.')
    else
    disp('Your number is greater than 10.')
    end

    Try running this program using various numbers for input.

    The switch\case structure is similar to the if structure, but has a few advantages. First of all it is easier to read and second, it is better if you are comparing strings (of possibly different lengths). The basic format is:

    switch (expression to test)
    case (case condition)
    (output in that case)
    case (case condition)
    (output in that case)

    ...(more cases)
    otherwise
    (do this if no cases are met)

    end

    Example 7.3.2: Using switch

    Let’s check to see if a cadet is in his\her first two years at VMI.

    Year = 'second class';

    switch Year
    case {'fourth class','third class'}
    disp('You are in the first two years.')
    case {'second class','first class'}
    disp('You are in the last two years.')
    otherwise
    disp('You must be a 5th year.')

    end

    The cases are grouped by curly brackets so that a case will be satisfied if the value of Year is any of the values in a specific case. Once this code is executed, the switch command will look at the value of Year and the output should be

    You are in the last two years.


    This page titled 7.2: 'if' and 'switch' commands was last modified on Sat, 31 Jul 2021 07:26:38 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Troy Siemers (APEX Calculus) via source content that was edited to the style and standards of the LibreTexts platform.