An interactive introduction to MATLAB

(Jeff_L) #1

62 loops



  • Lines 3–4 contain the body of the loop, in this case the value of the loop
    counter variablexis printed. Then the value ofxis incremented by 1.
    The value ofxmust be explicitly incremented otherwisexwill always
    be equal to 1, the conditionx<10will always be true, and the loop will
    therefore execute continuously.

  • Lines 6–23 contain the results of running thewhileloop.


Breaking out of a loop
If you end up stuck in an infinitely repeating loop use CTRL + C to force
MATLABto break out of the loop. However, under certain conditions you
may want your code to break out of a loop before it is finished. To do this
you can use thebreakcommand. Statements in your loop after thebreak
command will not be executed.

The while loop


(http://www.eng.ed.ac.uk/teaching/courses/matlab/unit05/while-
loop.shtml)

Self Test Exercise: while loops
Evaluate the following expressions without usingMATLAB. Check your an-
swers withMATLAB.


  1. How many times will this code printHello World?
    1 n = 10;
    2 while n > 0
    3 disp('Hello World')
    4 n = n−1;
    5 end

  2. How many times will this code printHello World?
    1 n = 1;
    2 while n > 0
    3 disp('Hello World')
    4 n = n + 1;
    5 end

  3. What values will this code print?
    1 a = 1
    2 while a < 100
    3 a = a* 2
    4 end

Free download pdf