An interactive introduction to MATLAB

(Jeff_L) #1

5 loops


Loops are another way of altering the flow of control in your program, and
provide methods for repeatedly executing commands. You might want to
repeat the same commands, changing the value of a variable each time, for a
fixed number of iterations. Alternatively, you might want to repeat the same
commands, changing the value of a variable each time, continually until a
certain condition is reached. Two of the most common types of loops,forand
while, will be examined in this chapter.

5.1 for loops


Aforloop is used to repeat a command, or set of commands, a fixed number
of times. Listing 5.1 shows the syntax of aforloop.
Listing 5.1: Syntax of aforloop
1 forvariable = f:s:t
2 statements
3 end


Comments:


  • Line 1 contains theforcommand, followed by the loop counter variable
    which is defined by an expression.fis the value of the loop counter on
    the first iteration of the loop,sis the step size or increment, andtis
    the value of the loop counter on the final iteration of the loop. As an
    example if the loop counter is defined by the expressionn = 0:5:15,
    which meansn = [0 5 10 15], on the first iteration of the loopn = 0, Refer to Chapter 1 if
    you need a refresher on
    ranges


on the second iterationn = 5, on the third iterationn = 10, and on the
forth, and final, iterationn = 15.


  • 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.


57
Free download pdf