SlideShare a Scribd company logo
MATLAB control structures continued

                       CIV1900: Engineering Skills
Recap
Control structures determine what gets executed

  • control flow is determined by control structures
  • MATLAB has four control structures

  • two for deciding between alternatives:
       • if statements
       • switch statements


  • two for repeating (a.k.a. looping or iteration):
       • while loops
       • for loops


  • MATLAB also has implicit loops over arrays



 CIV1900                     MATLAB control structures   3
An if statement runs the body when the condition is true

  • if statements are of the form:
    if <condition>
        <body>
    end

  • if and end are keywords (can't be used as variables)
  • <condition> is a logical expression which can be evaluated
    to true or false
  • <body> is the body of the if statement
       • one or more statements
       • only executed when the condition evaluates to true




 CIV1900                       MATLAB control structures         4
You can explore the conditions on their own

  • try all of these conditional operators:

  Operator   Description                    Operator       Description
  x > 4      greater than                   x < 4          less than
  x >= 4     greater than or equal to       x <= 4         less than or equal to
  x == 4     equal to                       x ~= 4         not equal to

  • for example:
  • >> x = 4
    >> x == 4
    ans = 1
  • equality is == to distinguish from assignment
  • remember ans is a logical not a number

 CIV1900                       MATLAB control structures                           5
What about if the condition is false?

  • an else clause can be run if the condition is false:
    if <condition>
      <true-body>
    else
      <false-body>
    end

  • else is also a keyword
  • <false-body> is run when the condition is false




 CIV1900                   MATLAB control structures       6
Else body only runs if none of the conditions are true

  • the general scheme looks like this:
    if <condition1>
       <true-body1>
    elseif <condition2>
       <true-body2>
    …
    else
       <false-body>
    end

  • where the elseif and else clauses are optional
  • and the elseif clause can be repeated for more conditions

 CIV1900                  MATLAB control structures             7
while statements are like repeating if statements

  • a while loop repeats the body while the condition stays true
  • the general scheme looks very similar to an if statement:
    while <condition>
       <body>
    end

  • while and end are keywords

  • when <condition> is false the loop will not execute again




 CIV1900                 MATLAB control structures                 8
The condition is evaluated before the body is executed

  • a while loop repeats the following steps
       • first, evaluating the conditional expression
       • if the condition is true, run the body
       • if the condition is false, jump to the statement after the body


  • an iteration is a single execution of the body
  • the condition is evaluated before each iteration begins

  • sometimes the body may never get executed




 CIV1900                        MATLAB control structures                  9
A very common idiom for while loops

     x = 1;
     while x <= 3
        fprintf('In the loop, x = %d n',x);
        x = x + 1;
     end
     fprintf('After the loop, x = %d n',x);

  • the output will look like this:
    In the loop, x = 1
    In the loop, x = 2
    In the loop, x = 3
    After the loop, x = 4

 CIV1900                   MATLAB control structures   10
Not updating the loop variable is a common mistake

  • what happens when we run this program?
    x = 1;
    while x <= 3
        fprintf('In the loop, x = %d n',x);
    end
    fprintf('After the loop, x = %d n',x);



  •   you can stop the infinite loop by pressing Control-C
  •   x is never updated in the body, so it stays at 1
  •   the condition is never false
  •   the loop never stops!

 CIV1900                   MATLAB control structures         11
Looping over array indices is common

     values = [1 5 2 8 -3 4];
     i = 1;
     total = 0;
     while i <= length(values)
        total = total + values(i);
        i = i + 1;
     end
     fprintf('The total is %d n',total);

  • the length function returns the length of a vector
  • the loop variable i ranges from 1 up to 6
  • single letter loop variables, especially i, j, and k are common

 CIV1900                  MATLAB control structures                   12
for loops simplify looping over arrays

  • for loops iterate over each element of an array or range

  • they have the general form
    for <variable> = <array>
         <body>
    end

  • <body> is run once for each element of the array

     for x = 1:3
        fprintf(‘x is now %d n’,x);
     end


 CIV1900                 MATLAB control structures             13
for loops really simplify our previous example

     marks = [75, 80, 71, 82, 86];

     total = 0;
     for m = marks
         total = total + m;
     end

     avg = total/length(marks);
     fprintf('Average mark %d n', avg);

  • variable m is assigned the value 75, then 80, then 71, …
  • after each time m is assigned, the for loop body is run

 CIV1900                  MATLAB control structures            14
for loops can be used with ranges

     for i = 1:2:8
         fprintf('i = %d n', i);
     end
     fprintf('after the loop i = %d n', i);

  • i will be assigned 1, then 3, then 5, …
  • so the output is
    i = 1                              Note:
    i = 3                              That the increment can
                                       also be negative e.g.
    i = 5
    i = 7                                      8:-2:1
    after the loop i = 7

 CIV1900                  MATLAB control structures             15
When we need the index, loop over 1:length(A)

 • for example, to find the index of the maximum in values:
   maxval = values(1);
   maxindex = 1;
   for i = 1:length(values)
         if values(i) > maxval
             maxval = values(i);
             maxindex = i;
         end
   end
   fprintf('max at index %d n', maxindex]);




 CIV1900                MATLAB control structures             16

More Related Content

Loops in matlab

  • 1. MATLAB control structures continued CIV1900: Engineering Skills
  • 3. Control structures determine what gets executed • control flow is determined by control structures • MATLAB has four control structures • two for deciding between alternatives: • if statements • switch statements • two for repeating (a.k.a. looping or iteration): • while loops • for loops • MATLAB also has implicit loops over arrays CIV1900 MATLAB control structures 3
  • 4. An if statement runs the body when the condition is true • if statements are of the form: if <condition> <body> end • if and end are keywords (can't be used as variables) • <condition> is a logical expression which can be evaluated to true or false • <body> is the body of the if statement • one or more statements • only executed when the condition evaluates to true CIV1900 MATLAB control structures 4
  • 5. You can explore the conditions on their own • try all of these conditional operators: Operator Description Operator Description x > 4 greater than x < 4 less than x >= 4 greater than or equal to x <= 4 less than or equal to x == 4 equal to x ~= 4 not equal to • for example: • >> x = 4 >> x == 4 ans = 1 • equality is == to distinguish from assignment • remember ans is a logical not a number CIV1900 MATLAB control structures 5
  • 6. What about if the condition is false? • an else clause can be run if the condition is false: if <condition> <true-body> else <false-body> end • else is also a keyword • <false-body> is run when the condition is false CIV1900 MATLAB control structures 6
  • 7. Else body only runs if none of the conditions are true • the general scheme looks like this: if <condition1> <true-body1> elseif <condition2> <true-body2> … else <false-body> end • where the elseif and else clauses are optional • and the elseif clause can be repeated for more conditions CIV1900 MATLAB control structures 7
  • 8. while statements are like repeating if statements • a while loop repeats the body while the condition stays true • the general scheme looks very similar to an if statement: while <condition> <body> end • while and end are keywords • when <condition> is false the loop will not execute again CIV1900 MATLAB control structures 8
  • 9. The condition is evaluated before the body is executed • a while loop repeats the following steps • first, evaluating the conditional expression • if the condition is true, run the body • if the condition is false, jump to the statement after the body • an iteration is a single execution of the body • the condition is evaluated before each iteration begins • sometimes the body may never get executed CIV1900 MATLAB control structures 9
  • 10. A very common idiom for while loops x = 1; while x <= 3 fprintf('In the loop, x = %d n',x); x = x + 1; end fprintf('After the loop, x = %d n',x); • the output will look like this: In the loop, x = 1 In the loop, x = 2 In the loop, x = 3 After the loop, x = 4 CIV1900 MATLAB control structures 10
  • 11. Not updating the loop variable is a common mistake • what happens when we run this program? x = 1; while x <= 3 fprintf('In the loop, x = %d n',x); end fprintf('After the loop, x = %d n',x); • you can stop the infinite loop by pressing Control-C • x is never updated in the body, so it stays at 1 • the condition is never false • the loop never stops! CIV1900 MATLAB control structures 11
  • 12. Looping over array indices is common values = [1 5 2 8 -3 4]; i = 1; total = 0; while i <= length(values) total = total + values(i); i = i + 1; end fprintf('The total is %d n',total); • the length function returns the length of a vector • the loop variable i ranges from 1 up to 6 • single letter loop variables, especially i, j, and k are common CIV1900 MATLAB control structures 12
  • 13. for loops simplify looping over arrays • for loops iterate over each element of an array or range • they have the general form for <variable> = <array> <body> end • <body> is run once for each element of the array for x = 1:3 fprintf(‘x is now %d n’,x); end CIV1900 MATLAB control structures 13
  • 14. for loops really simplify our previous example marks = [75, 80, 71, 82, 86]; total = 0; for m = marks total = total + m; end avg = total/length(marks); fprintf('Average mark %d n', avg); • variable m is assigned the value 75, then 80, then 71, … • after each time m is assigned, the for loop body is run CIV1900 MATLAB control structures 14
  • 15. for loops can be used with ranges for i = 1:2:8 fprintf('i = %d n', i); end fprintf('after the loop i = %d n', i); • i will be assigned 1, then 3, then 5, … • so the output is i = 1 Note: i = 3 That the increment can also be negative e.g. i = 5 i = 7 8:-2:1 after the loop i = 7 CIV1900 MATLAB control structures 15
  • 16. When we need the index, loop over 1:length(A) • for example, to find the index of the maximum in values: maxval = values(1); maxindex = 1; for i = 1:length(values) if values(i) > maxval maxval = values(i); maxindex = i; end end fprintf('max at index %d n', maxindex]); CIV1900 MATLAB control structures 16

Editor's Notes

  1. could be implemented with two opposite if statements but this would be error prone and repetitive