MATLAB Module 5: Conditional Statements and Loops

Conditional Statements

Uses of the if-end Construct

  • The if-end decision construct is used to decide whether to execute a sequence of commands based on relational operations.
  • Uses:
    • Displaying messages.
    • Preventing undesired operations, such as skipping log(x) for x0x \le 0. MATLAB can handle the log of a negative number as a complex number.

Basic if-end Construct

  • Form:

    if comparison
      action
    end
    
  • Keywords: if and end

  • Execution:

    • If the comparison is true, the action is executed.
    • If the comparison is false, the program skips to the end statement.

Example 1

  • Example:

    if b^2 - 4*a*c > 0
      x1 = -(b + sqrt(b^2 - 4*a*c))/(2*a)
      x2 = -(b - sqrt(b^2 - 4*a*c))/(2*a)
    end
    

if-end Constructs with Arrays

  • When the comparison includes an array, all elements are compared.
  • An if construct requires all elements to be true for the action to be executed.
  • If some elements are false, the program skips to end.

elseif

  • The elseif keyword is optional.

  • It is useful when multiple comparisons need to be tested.

  • Example:

    if grade >= 85
      fprintf('HD\n');
    elseif grade >= 75
      fprintf('D\n');
    elseif grade >= 65
      fprintf('C\n');
    elseif grade >= 50
      fprintf('P\n');
    elseif grade < 50
      fprintf('F\n');
    end
    
  • The first elseif statement that is true will be executed, and the others are ignored.

else

  • The else command is an optional keyword in an if-end construct.
  • When the if comparison is false, commands after else are executed.
  • There can only be one else keyword.

Switch-Case Keywords

  • Keywords:
    • switch
    • case
    • otherwise
    • end
  • switch is followed by a switch expression/variable (user choice).
  • The switch expression must be a scalar number or string.
  • case allows adding statements based on a choice.
  • otherwise is an optional keyword and functions like the else keyword in an if-end structure.

Structure of switch/case

  • Structure:

    switch variable/switch expression
      case option1
        code to be executed if variable is exactly equal to option1
      case option2
        code to be executed if variable is exactly equal to option2
      case option_n
        code to be executed if variable is exactly equal to option_n
      otherwise
        code to be executed if variable is not equal to any of the options
    end
    

Switch-Case Construct

  • This is a decision construct that is an alternative to the if-end structure.
  • The code is generally easier to read.
  • Allows choosing between multiple outcomes based on a criterion, which must be exactly true.

When to Use switch/case

  • The criterion can be a scalar (a number), a string, or a character.
  • In practice, it is used more with strings than with numbers.

Example: Fuel Price Determination

  • Suppose you want to determine the fuel price based on fuel type.
  • Available fuel types:
    • Ethanol 94 (E94)
    • Ethanol 105 (E105)
    • Unleaded 91 (U91)
    • Premium 95 (U95)
    • Premium 98 (U98)
    • Diesel (DL)
    • Premium Diesel (PDL)

if-end Approach

  • Example:

    code = input('Enter fuel type code :','s')
    if strcmp(code,'E94')
      price = 118.9;
    elseif strcmp(code,'E105')
      price = 128.9;
    elseif strcmp(code, 'U91')
      price = 121.9;
    elseif strcmp(code ,'U95')
      price = 131.9;
    elseif strcmp(code,'U98')
      price = 138.9;
    elseif strcmp(code,'DL')
      price = 131.9;
    elseif strcmp(code,'PDL')
      price = 137.9;
    else
      price = nan;
    end
    if ~isnan(price)
      disp(['Fuel price for ',code,' is ',num2str(price)]);
    else
      disp(['Unknown fuel type ',code]);
    end
    

switch-case Approach

  • Example:

    code = input('Enter fuel type code :','s')
    switch code
      case 'E94'
        price = 118.9;
      case 'E105'
        price = 128.9;
      case 'U91'
        price = 121.9;
      case 'U95'
        price = 131.9;
      case 'U98'
        price = 138.9;
      case 'DL'
        price = 131.9;
      case 'PDL'
        price = 137.9;
      otherwise
        price = nan;
    end
    if ~isnan(price)
      disp(['Fuel price for ',code,' is ', num2str(price)]);
    else
      disp(['Unknown fuel type ',code]);
    end
    

For Loops

Repetition Structures

  • 'Loops' are used to repeat a set of instructions multiple times.
  • MATLAB supports two types of loops:
    • for loops
    • while loops

Concept of the for Loop

  • The for loop is a MATLAB construct that allows a sequence of MATLAB statements to be executed more than once.
  • The for loop repeats a block of commands for a specified number of times; the specified number is established before the loop is executed.

Construction of for Loops

  • The for loop construct:

    for index = [range of values in array format]
      command #1
      command #2
      command #3
      ...
    end
    
  • The loop is executed once for each element of the index matrix identified in the first line.

for Loop Example 1

  • Example:

    % for loop example 1
    for k=[1 2 7 10]
      k
    end
    
  • A 4-element array is the index array.

  • Displays k in each iteration.

for Loop Example 2

  • Example:

    for n = 1:5
      fprintf('The value of n is now %d\n',n);
    end
    

    Note: Change the steps n = 1:5 to n = 1:0.5:5 and execute the script to show that n does not have to be an integer.

  • Output:

    The value of n is now 1
    The value of n is now 2
    The value of n is now 3
    The value of n is now 4
    The value of n is now 5
    

Exercise

  • vector_1 contains the values of n, i.e.: vector_1 = [1 2 3 4 5]

  • vector_2 contains the squares of n, i.e.: vector_2 = [1 4 9 16 25]

  • You can use a loop to define, element by element, a vector; this illustrates how a for loop works.

  • Example:

    for n=1:5
      fprintf('The value of n is now %d\n' ,n);
      vector_1(n)=n;
      vector_2(n)=n^2;
    end
    

Let us create a conversion chart

  • Degrees-to-Radians
    • Create a table that converts angles from degrees to radians, from 0 to 360 degrees in increments of 10 degrees.
  • Inputs and Outputs
    • Input: Define an array of angles in degrees.
    • Output: Display a table of angles in degrees and the corresponding values in radians.

The conversion table code

  • Code:

    fprintf('Degrees to Radians \n')
    fprintf('Degrees     Radians \n')
    for degrees = 0:10:360
      radians = (pi./180).* (degrees);
      fprintf('%8.0f %8.2f \n', degrees, radians)
    end
    % the function deg2rad() can be used instead
    

Exercise

  • Create a table that illustrates the relationship between temperature in degrees Celsius and the corresponding temperature in degrees Fahrenheit, from -40 to 100 degrees C in increments of 5 degrees. The conversion formula is as follows:
  • Check the temperatures that we all may know the conversion, e.g., 0 C = 32 F, and 100 C = 212 F.
  • The conversion formula is: F=95C+32F = \frac{9}{5}C + 32

While Loops

Concept of while loops

  • Recall from previous lectures, loops are MATLAB constructs that allow a sequence of MATLAB commands to be executed more than once.
  • A while loop repeats a block of commands as long as an expression controlling it is true (logical 1).

The while loop construct

  • Construction of a while loop:

    while condition
      command #1
      command #2
      command #3
      …
    end
    
  • The loop ends when the condition is false (logical 0); code block is repeated while condition is true (logical 1).

A while loop example

  • One way of controlling the loop is to define a counting index; in this case we start with n = 0.

  • After the while keyword, an expression is defined that allows the loop to execute as long as the expression is true; in this case the loop runs until n > 5.

  • The counter must, of course, be changed in the loop, or the loop will run forever (infinite loop). In this case n is increased by 1 each time the block of commands in the loop is executed.

  • Example:

    n = 0;
    while n <= 5
      fprintf('The value of n is now %d\n');
      n = n+1;
    end
    

Another Example

  • A program to sum a series of numbers input by a user:

    a = 1;
    n = 0;
    myTotal = 0.0;
    while a >= 0
      a = input('Enter a number to add to the running ... total (neg # to end): ');
      if a>=0
        myTotal = myTotal + a;
        n = n + 1;
      end
    end
    fprintf('The sum of the %d numbers you input is . . . %12.3f\n',n,myTotal);
    % Note that the if >= 0 and end statements are needed in
    % this example.
    

User input validation

  • In this example we want to ensure that the user inputs data in the correct range:
  • This loop will repeat until the user has entered a non-negative number (n0n \ge 0)

Exercise

  • Write MATLAB code that calculates the factorial of a number using a while loop.

    a = 1;
    count = 1;
    while count < x
      count = count + 1;
      a = a * count;
    end
    output = a;
    

Break and Continue

  • Are optional keywords in for loops and while loops
  • break causes the loop to terminate prematurely
  • continue causes MATLAB to skip a pass through the loop, but continue on until the criteria for ending is met
  • Both are used typically in conjunction with an if statement

Example - Continue

  • Determine the sum: S=n=1,n410n(n2+1)4S = \sum_{n=1, n \ne 4}^{10} \frac{n(n^2 + 1)}{4}

    total = 0;
    for n=1:10
      if n==4
        continue
      end
      total = total + n*(n^2+1)/4;
    end
    disp(total);
    

Break - Example

```matlab
while (1)
  % calculations
  %  - store the previous result to prev_value
  %  - update the current value and store that in current_value
  % check for the difference between the previous
  % iteration and current iteration - delta
  % delta = current_value - prev_value
  % if the difference between the two is smaller
  % than a set limit - end computations
  if (delta < 0.001)
    break
  end
end
```