| Programming and Data Types | ![]() |
The for loop executes a statement or group of statements a predetermined number of times. Its syntax is:
forindex = start:increment:endstatementsend
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.
for i = 2:6
x(i) = 2*x(i-1);
end
You can nest multiple for loops.
for i = 1:m
for j = 1:n
A(i,j) = 1/(i + j - 1);
end
end
Note
You can often speed up the execution of MATLAB code by replacing for
and while loops with vectorized code. See "Vectorization of Loops" on page
1-91 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
for i = A
statements
end
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 | ![]() |