Programming and Data Types |
The for
loop executes a statement or group of statements a predetermined number of times. Its syntax is:
The default increment is 1
. You can specify any increment, including a negative one. For positive indices, execution terminates when the value of the index exceeds the end
value; for negative increments, it terminates when the index is less than the end value.
For example, this loop executes five times.
You can nest multiple for
loops.
Note
You can often speed up the execution of MATLAB code by replacing for and while loops with vectorized code. See the section "Vectorizing Loops" for details.
|
Using Arrays as Indices
The index of a for
loop can be an array. For example, consider an m
-by-n
array A
. The statement
sets i
equal to the vector A(:,k)
. For the first loop iteration, k
is equal to 1
; for the second k
is equal to 2
, and so on until k
equals n
. That is, the loop iterates for a number of times equal to the number of columns in A
. For each iteration, i
is a vector containing one of the columns of A
.
while | continue |