for Loop
A for
loop has the structure :
for k = [ list of values of k to be used in the loop ] do statements (may use current value of k) % BODY OF LOOP end
The for
loop is interpreted as follows:
The variable k
is often called a counter or control variable.
This variable will take on each successive value of the vector in the first line of the loop.
The current value of k
can be used inside of the body of the for
loop.
Any valid variable name can be used for the control variable.
Common choices are: i
, j
, k
, and n
.
The control flow diagram of a for
loop looks like:
The list of values for k can be created using the colon operator.
This gives us a convenient way to create a count-controlled loop.
The structure of this type of for
loop is:
for counter = first : increment : last statements % body of for loop end
The code first:increment:last
creates a vector like the vectors we have
created using the colon (:
) operator in earlier lessons.
The count-controlled for
loop is equivalent
(and preferred) to the following while
loop:
counter = first; while counter <= last statements % body of the loop counter = counter + increment; end
We can leave out the increment
part of the condition.
If we leave it out, Matlab uses an increment of 1.
In other words, first:last
is equivalent to first:1:last
(just as it was when we used the colon operator to create and manipulate matrices).