An interactive introduction to MATLAB

(Jeff_L) #1

58 loops


Indenting for readability
It is good practice to indent the body of loops for readability in your script
files.MATLABwill usually do this for you, but if not, highlight your code
and choose Smart Indent from the Text menu in the Editor Window toolbar.
Listing 5.2 gives an example of a simpleforloop which displays the value
of the variablex.
Listing 5.2: Simple example of aforloop
1 >> for x=1:1:9
2 x
3 end
4 x =
5 1
6 x =
7 2
8 x =
9 3
10 x =
11 4
12 x =
13 5
14 x =
15 6
16 x =
17 7
18 x =
19 8
20 x =
21 9

Comments:


  • In Line 1 the loop counter variable, in this casex, is defined to start at 1
    and count up in steps of 1 until 9.

  • In Line 2 the body of the loop prints the value of the loop counter variable
    x.

  • When the loop is executed, initially the value of 1 is assigned tox, and
    then the body of the loop is executed. The value ofxis then incremented
    by 1, the body of the loop is executed again, and so on untilxis 9.
    Whereupon, the body of the loop is executed for a final time and then
    the loop terminates.

  • Lines 4–21 contain the results of running theforloop.

Free download pdf