Skip to main content
Engineering LibreTexts

6.3: if, else, elseif

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

    Most of the following explanations of if, else, elseif, usage are primarily from Donald Dabdub, ConditionalStatements_FlowControl.pdf,

    One example is by Carey Smith.

    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 )

    • The “test condition” is any combination of relational and logical operators used to compare different variables or 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, or 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, these statements will not be executed

    Sample case 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.


    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 example

    x = 5 % Set x=5 to demonstrate how the if logic works.
    if (x < 0) % This is false for x=5,
        % so the following 2 lines of code are not executed
        z = 100;
    else % The following commands are executed when (x < 0) is false.
        z = 200;
        pause(0.6) % wait 0.6 seconds between beeps)
    z % show the value of z


    Add example text here.


    Watch this video (Logical operators in MATLAB, Robert Talbert) before studying the next example:


    if, elseif, else statement

    If you have 2 or more 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

    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, else Grade (Practice Problem)
    • Precondition: the user sets the variable score to a value between 0 and 100.
    • Use an if, elseif statement to determine the user’s equivalent letter grade;
      • A for score >=90
      • B for score < 90 and >=80
      • C for score < 80 and >=70
      • D for score < 70 and >=60
      • F for score < 60
    • (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

    % Precondition: Set variable score = to 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'
        disp('score is not valid') % Perhaps score is a character, not a number

    Example \(\PageIndex{4}\) if, elseif, else name length

    By Carey Smith

    This script tests the length of a name and determines if it is short, medium, or long.

    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'])


    Add example text here.


    Exercise \(\PageIndex{2}\) if_else_drivers_test

    Figure out the code for this exercise:

    On the California written drivers license test, you need to score at least 30 out of 36 to pass.
    Write a script that does the following:
    A. (1 pt) Has an precondition (input) of a variable named score.
    B. (2 pts) If score is greater than or equal to 30,
    then the script displays this message:
    'Congratulations, you passed.'
    C. (2 pts) Else, if score is greater than 25 (but less than 30),
    then the script displays this message:
    'You did not pass, but were close.'
    D. (2 pts) Else, the script displays this message:
    'You need to study a lot before taking the test again.'


    Add texts here. Do not delete this text first.


    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 example

    The adds + or - to a grade, such as A+ or A-

    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) = '+';
        disp(grade) % This displays the value of the variable grade
        disp('B or worse')


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

    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?: ');
            disp('You did very well... for a young person')
        elseif(age<=21 & age>18)
            disp('You did pretty well... for a young person')
            disp('You are old')
        disp('Your score is too low')

    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


    Add example text here.


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

    This video offers shows nested if-elseif-else-end logic and shows a flowchart of the logic:

    Branching structures in MATLAB- IF-ELSE (Robert Talbert)



    This page titled 6.3: if, else, elseif is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith.