Conditions

Loops provide a means to execute part of the script multiple times. Conditions provide the route to choose whether or not to execute part of a script.

Open a new MATLAB script conditions.m and type the following;

for i = 1 : 10
      
      if i < 7
      
          fprintf('%d is less than 7.\n', i)
          
      elseif i > 7
      
          fprintf('%d is greater than 7.\n', i)
      
      else
      
          fprintf('%d is equal to 7.\n', i)
      
      end
      
      end

Use fprintf to directly display the text without creating a variable. However, to terminate the display properly, you must end the text with the newline (\n) metacharacter.

This script loops i over all values from 1 to 10, and uses an if block to test each value of i. There are three sections to the if block:

  • The if condition if i < 7. This is a test (condition) which is evaluated to be true or false. If it is true (in this case i is less than seven) then the indented block of code below the condition is executed.
  • The elseif (shorthand for “else if”) condition elseif i > 7. This is a test that is evaluated only if the above test is evaluated as false. This test is also evaluated as true or false. If it is true (in this case i is greater than seven) then the indented block of code below this condition is executed. The elseif condition is optional, and you can have multiple elseif conditions one after another.
  • The else condition else. This presents a indented block of code that is executed if, and only if all of the above if and elseif conditions evaluate to false. This provides the default code that is executed in case none of the above conditions are true. The else condition is optional, but unlike the elseif, there can only be one else condition per if block.


Previous | Up | Next