FOR For Loop
Section: Flow Control
Usage
Thefor
loop executes a set of statements with an
index variable looping through each element in a vector.
The syntax of a for
loop is one of the following:
for (variable=expression) statements end
Alternately, the parenthesis can be eliminated
for variable=expression statements end
or alternately, the index variable can be pre-initialized with the vector of values it is going to take:
for variable statements end
The third form is essentially equivalent to for variable=variable
,
where variable
is both the index variable and the set of values
over which the for loop executes. See the examples section for
an example of this form of the for
loop.
Examples
Here we writefor
loops to add all the integers from
1
to 100
. We will use all three forms of the for
statement.
--> accum = 0; --> for (i=1:100); accum = accum + i; end --> accum ans = 5050
The second form is functionally the same, without the extra parenthesis
--> accum = 0; --> for i=1:100; accum = accum + i; end --> accum ans = 5050
In the third example, we pre-initialize the loop variable with the values it is to take