Conditional statements

Conditional statements

Conditional statements are examples of "branching behavior", and they allow your code to perform different tasks depending on certain conditions.

There are a few different forms:

  • if
  • if-else/elseif
  • switch-case

"if"

An if statement allows a block of code to be executed only when certain conditions hold.


        if a < 10
            b = 1
        end
    
  • An if statement starts with the "if" keyword.
  • A condition follows if.
  • It ends with the keyword "end"
  • Any list of statements can be included in between.
  • Indentations improve readability.

if-else

An if block can include alternate choices.


        if a < 10
            b = 1
        else
            b = 2
        end
    

if-else/elseif

An if block can include multiple choices.


        if a < 10
            b = 1
        elseif a < 20
            b = 2
        else
            b = 3
        end
    

Logical operators

Multiple logical expressions can be combined together using logical operators.

  • Logical AND (with short-circuit): &&
  • Logical OR (with short-circuit): ||
  • Logical NOT ~

        if (a > 3) && (a < 10)
            b = 1
        end
    

Let's try

Read the following code and explain what it does.


        M = magic(5);
        for i = 1:5
            for j = 1:5
                if M(i,j) < 4
                    M(i,j) = 0;
                elseif M(i,j) < 6
                    M(i,j) = 1;
                else
                    M(i,j) = 2;
                end
            end
        end
    
  • Count the number of entries in magic(5) that are less than 10 / greater than 20.
  • Recreate the following image

More exercises

Can you recreate this image using "for" and "if"?

More exercises

What about this?