An interactive introduction to MATLAB

(Jeff_L) #1
5.2while loops 61

Comments:


  • Line 1 contains thewhilecommand, followed by a condition e. g.x>10.
    This means as long as the condition,x>10, remains true the loop will
    continually repeat.

  • Line 2 contains the body of loop which can be a command or series of
    commands that will be executed on each iteration of the loop.

  • Line 3 contains theendcommand which must always be used at the end
    of a loop to close it.
    Listing 5.5 gives an example of a simplewhileloop which displays the value
    of the variablex.
    Listing 5.5: Simple example of awhileloop
    1 >> x=1;
    2 >> while x<10
    3 x
    4 x=x+1;
    5 end
    6 x =
    7 1
    8 x =
    9 2
    10 x =
    11 3
    12 x =
    13 4
    14 x =
    15 5
    16 x =
    17 6
    18 x =
    19 7
    20 x =
    21 8
    22 x =
    23 9


Comments:


  • Line 1 assigns the value of 1 to the variablex. Notice this is outside of
    thewhileloop. If you don’t do this you will get an error because you
    are testing whetherx<10butxhas never been defined. Remember to define
    variables you use in
    loops before you start
    the loops themselves.

  • In Line 2 the condition,x<10, is specified. In this case the loop will
    continue to repeat as long asxis less than 10. As soon asxis equal to
    10 execution of the loop is stopped.

Free download pdf