Skip to main content
Library homepage
 
Engineering LibreTexts

6.5: if, else, elseif, error() Parts 2 and 3

  • Page ID
    84412
  • \( \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}}\)

    Subsection if, else, elseif

    The following explanations of if, else, elseif, usage are from Donald Dabdub, ConditionalStatements_FlowControl.pdf

    Often we want to execute a command only if a certain test condition is satisfied. We use if statements to do this. Simple if statement

    If you want to execute certain commands only when a certain test condition is met, use a simple if statement of the form:

    if ( test condition )
      commands
    end

    • The “test condition” is any combination of relational and logical operators used to compare different variables/data.
    • You don’t need the parentheses around the test condition, but it is a good idea to use parenthesis to improve code readability and avoid confusion and mistakes. Always make sure your parenthesis are balanced to prevent errors.
    • The “commands” are any commands/statements/calculations that you have learned in MATLAB.
    • An end is required for every opening if, which signifies the end of all commands that depend on the test condition. Anything outside of the if statement (before the opening if or after the closing end) is executed regardless of whether or not the test condition is satisfied – only the commands inside the if statement depend on the test condition.
    • The indentation for the statements inside the if is not required but greatly improves the readability of presentation of the code. MATLAB will even automatically do indentation for you – simply select all the text in your M-File and right click for the “Smart Indent” option (CNTRL + I on Windows). Indentation is always recommended.
    • Note that MATLAB is case sensitive – do not capitalize any letters in “if” or “end” as doing so will produce errors.
    Example \(\PageIndex{1}\) if x, y example

    Let’s jump right into an example to see how if statements work.
    In myfile.m:
    x = 5.4
    y = 10
    if (x>4) % if the test condition is true, the following two lines will be executed
      y = y + 1;
      x = 2; % if the test condition is false, the statements will not be executed
    end
    Sample cases:
    Initial values:

    x = 5.4000

    y = 10

    Final values:

    x = 2

    y = 11

    In the example above, the test condition on the if statement was satisfied (it was true) since the value stored in x was indeed great than 4. Because the test condition was true, the statements inside the if were executed, and the final values of x and y after the if statement were different than the initial values.

    Solution

    Add example text here.

     

    if/else statement:

    An if/else statement will allow you to execute certain commands if a test condition is true and execute other commands if the test condition is false. The commands inside the else are executed only if the test condition on the if statement is false. If the test condition on the if statement is true, the commands inside the if are executed, and the commands inside the else are skipped. Thus, only the commands inside the if or the commands inside the else will be executed, never both. Let’s look at an example of an if/else construct to illustrate.

    Example \(\PageIndex{2}\) if/else x, y example

    x = 5
    y = 10
    if (x>y) % Execute the next two lines if the test condition is true
        y = x;
        z = 100;
    else
        z = 200; % Execute this line if the test condition is false
    end

    Final values:

    x = 5

    y = 10

    z = 200

    Solution

    Add example text here.

    if/elseif/else statement

    If you have 2+ separate conditions that you need to check, but only one can be satisfied at a time, you can use an if/elseif statement. In an if/elseif statement, a series of possible conditions are checked in order. The order is important because as soon as one condition is satisfied, the commands inside of that if (or elseif) are executed, and no other conditions are checked (i.e., all of the other elseif and an else if it exists are skipped).

    Example \(\PageIndex{3}\) if/elseif x,y example

    x = 5;
    if (x<0) % This is false, so the following commands are not executed
        z = 100;
        beep
    elseif (x>=0 & x<10)% This is true, so the following commands are executed
        z = 200; % and the if statement ends
        beep, beep
    elseif (x<=10) % This is true, but is not executed, since the previous was true
        z = 300;
        beep, beep, beep
    end

    Solution

    Sample output:
    z = 200 (with 2 beeps)

    Note that once a test condition is found to be true, the statements inside that test condition are executed and the if/elseif statement is terminated even if later test conditions would be true too. This brings up a few important points to remember when using an if/elseif construct:

    • Only one condition on an if/elseif can be true.
    • * If you have 2 or more conditions that need to be checked and it is possible for both of them to be true simultaneously, you should use separate if statements rather than an if/elseif.
    • When using an if/elseif, be careful with the order in which you enter your test conditions.
    • The following practice problem should be solved to illustrate this point is the following (solve this problem before proceeding with the notes)
    Exercise \(\PageIndex{1}\) if/elseif score/grade Practice Problem
    • Allow the user to enter their score on a 0-100 scale. Use an if/elseif statement to determine the user’s equivalent letter grade with A being >=90, B being >=80, C being >=70, and D being >=60, and all other scores considered F.
    • (Do this without using compound relations; that will come later.)
    • Be careful! Putting test conditions in the wrong order will produce incorrect output for the letter grade. Be sure to test your code with an input in each of the grade ranges.
    • Including an else on an if/elseif is optional. An else is never required. Remember that it is only executed if all other test conditions are false
    Answer

    % Precondition: Set variable score = a value between 0 and 100
    if (score >= 90)
        grade = 'A'
    elseif (score >= 80)
        grade = 'B'
    elseif (score >= 70)
        grade = 'C'
    elseif (score >= 60)
        grade = 'D'
    elseif (score >= 0)
        grade = 'F'
    else
       disp('score is not valid')
    end

     

    if, elseif, else nameExample \(\PageIndex{4}\)

    name_in = input('Enter your name: ','s')
    name_len = length(name_in) % Number of letters in the name

    if(name_len <= 4)  % Is the name <= 4 letters?
      disp([name_in,' is a short name'])
      
    elseif(name_len <= 7) % The name is > 4 letters; is the name <= 7 letters?
      disp([name_in,' is a medium name'])
      
    else   % the name > 7 letters
      disp([name_in,' is a long name'])
    end

    Solution

    Add example text here.

    Solution

    Add example text here.

     

    Nested if statements

    You can put if statements within if statements; this is called nesting and if statement. This is typically done if you only want to check a certain condition if another condition has already been satisfied. Thus, in this construct the nested if statement will be checked only when the if statement that it is inside of becomes true. Let’s look at an example to illustrate.
     

    Example \(\PageIndex{5}\) Nested if statements score/grade example

    In myfile.m:
    % The input() function displays a message, then stores the user's input in the variable "score"
    score = input('Enter your score: ');

    disp('Your grade is:')
    if((score<=100) & (score>=90)) % This compound logic is only true if both parts are true.
        grade(1) = 'A';
        if(score>=90 & score<93) % This if statement is inside the previous if statement. 
            grade(2) = '-'; % the variable grade has 2 characters
        elseif(score>=93 & score<97)
            grade(2) = ' ';
        elseif(score>=97 & score<=100)
            grade(2) = '+';
        end
        disp(grade) % This displays the value of the variable grade
    else
        disp('B or worse')
    end

    Solution

    Sample output:
    >> myfile
    Enter your score: 97.5
    Your grade is:
    A+

    In this example, we only check the nested if statement if the score is within the range for an A grade. If the score is not within this range, the statements inside the else are executed and the nested if statement is skipped entirely.

    We will execute the next example twice, with different input values to illustrate the behavior of the nested if statement. In the second execution, the nested if statement will be skipped entirely because the score is not greater than 90. Just remember in the nested if construct, the nested if statements are only checked when the outside if statement that they are inside of becomes true.

    Example \(\PageIndex{6}\) Nested if logic score and age

    In myfile.m:
    score = input('What was your test score?: ');
    age = input('How old are you?: ');
    if(score>90)
        if(age<=18)
            disp('You did very well... for a young person')
        elseif(age<=21 & age>18)
            disp('You did pretty well... for a young person')
        else
            disp('You are old')
        end
    else
        disp('Your score is too low')
    end

    Sample run #1:
    >> myfile
    What was your test score?: 91
    How old are you?: 14
    You did very good... for a young person    

    Sample run #2:
    >> myfile
    What was your test score?: 81
    How old are you?: 55
    Your score is too low

    Solution

    Add example text here.

     

    Subsection if, else with Error Checking

    An if-else example with an error() message is given here.

    Example \(\PageIndex{6}\) add2() function with error checking

    previously we saw the add1() function, which adds 2 vectors. add1() assumed that the 2 vectors were the same length, but did not check that.

    Here we create add2(), which checks that the 2 vectors are the same length.

    add2.m:

    function result = add2(a, b)
    % This adds vectors a and b
    % The output is "result"
    % This function first checks to see that a and b are the same length
    a_len = length(a)
    b_len = length(b)
    if(a_len == b_len) % If the a and b vectors are the same length, then it adds a and b
        result = a + b;
    else % else, the vectors are different lengths, so it creates an error message
        result = 0
        error('length(a) must = length(b)')
    end

     

    The functions add1() and add2() are tested by add2_test.m, which is listed here:

    %% Test add functions
    % (1 pt) Clear any variables etc.
    clear all; close all; format compact; clc;

    %% First, test add1.m and add2.m with 2 vectors that are the same length
    x = 1:4
    y = [0, 1, 10, 100]
    z = add1(x,y)

    z = add2(x,y)

    %% Second, test add1.m and add2.m with 2 vectors that are not the same length
    w = [1, 2]
    y = [0, 1, 10, 100]

    z = add2(w,y)

    z = add2(w,y)

     

    Solution

    Add example text here.

     

    This video from "SnugglyHappyMathTime" shows a couple of fun examples:

     

    Exercise \(\PageIndex{2}\) Area of a Square

    (1 pt) Write a function that computes the area of a square.

    % (1 pt) Use the input function to get the length of a side with this code: 
    s = input('Enter the length of one side of a square: ');
    % The input() function displays the message, then reads a number and stores it in the variable s

    % Next, your function will check that the input value is a single number and is >= 0.

    % (2 pts) Check that s is a single number by finding the length of s:
    % s_len = length(s)
    % If s_len is not 1, then display s. 

    % Also, generate this error message:
    error('Area_of_square.m: the input must be a single number')
    % The error() function will cause the program to stop.

    % (2 pts) After the check of s_len, check that the value of s is >= 0 
    % If s is negative, then display s and generate this error:
        error('Area_of_square.m: the input is < 0')

    % (2 pts) After both of these checks, compute the area of the square. This is the output of the function

    % Test it with these input values:
    s = 3
    s = -1
    s = 1:3

    Answer

    function sq_area = Area_of_square(s)
    % Area_of_square script
    % (1 pt) Write a script that computes the area of a square.
    % (1 pt) Use the input function to get the length of a side 
    %       with this function: 
    s = input('Enter the length of one side of a square: ');
    % The input() function displays the message, then reads a number and stores it in the variable s

    % (2 pts) This script only works for a scalar input, not a vector.
    % Check that s is a single number:
    s_len = length(s);
    % If s_len is not 1, then display s and generate this error:
    if (s_len ~= 1)  
        disp(['s= ',num2str(s)]) % Display s
        error('Area_of_square.m: the input must be a single number')
    end

    % (2 pts) Check that the value of s is >= 0 (The side can't be < 0)
    % If s is negative, then display s and generate this error:
    if (s < 0)  
        disp(['s= ',num2str(s)]) % Display s
        error('Area_of_square.m: the input is < 0')
    end

    % (2 pts) Compute the area of the square.
    sq_area = s^2
     

     

    Homework: 

    Area of a circle

    % (1 pt) Write a function that computes the area of a circle.
    % (1 pt) Use the input function to get the radius with this function: 
    r = input('Enter the radius of a circle: ');  % Note the space after the colon
    % The input() function displays the message, then reads a number and stores it in the variable r

    % (2 pts) Check that r is a single number. 
    % Use r_len = length(r) to find the length of r
    % If r_len is not 1, then display r and generate this error:
    error('Area_of_circle.m: the input must be a single number')
    % (2 pts) Check that r is >= 0
    % If r is negative, then display r and generate this error:
        error('Area_of_circle.m: the input is < 0')
    % (2 pts) Compute the area of the circle. 

    % Test your function with these input values:
    r = 3
    r = -1
    r = 1:3

    Since these are entered via the input() function, you do not need a test file.


    6.5: if, else, elseif, error() Parts 2 and 3 is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.