for - for loop to repeat specified number
of times - MATLAB (original) (raw)
for
loop to repeat specified number of times
Syntax
for index
= values
statements
end
Description
for _`index`_ = _`values`_, _`statements`_, end
executes a group of statements in a loop for a specified number of times. values
has one of the following forms:
initVal
:
endVal
— Increment theindex
variable from_initVal
_ toendVal
by1
, and repeat execution of_statements
_ untilindex
is greater thanendVal
.initVal
:
step
:
endVal
— Incrementindex
by the value_step
_ on each iteration, or decrements_index
_ whenstep
is negative.valArray
— Create a column vector,index
, from subsequent columns of arrayvalArray
on each iteration. For example, on the first iteration,_`index`_ = _`valArray`_(:,1)
. The loop executes a maximum ofn
times, wheren
is the number of columns ofvalArray
, given bynumel(_`valArray`_(1,:))
. The inputvalArray
can be of any MATLAB® data type, including a character vector, cell array, or struct.
Examples
Create a Hilbert matrix of order 10.
s = 10; H = zeros(s);
for c = 1:s for r = 1:s H(r,c) = 1/(r+c-1); end end
Step by increments of -0.2
, and display the values.
for v = 1.0:-0.2:0.0 disp(v) end
1
0.8000
0.6000
0.4000
0.2000
0
for v = [1 5 8 17] disp(v) end
for I = eye(4,3) disp('Current unit vector:') disp(I) end
Tips
- To programmatically exit the loop, use a break statement. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement.
- Avoid assigning a value to the
index
variable within the loop statements. Thefor
statement overrides any changes made toindex
within the loop. - To iterate over the values of a single column vector, first transpose it to create a row vector.
Extended Capabilities
Usage notes and limitations:
Suppose that the loop end value is equal to or close to the maximum or minimum value for the loop index data type. In the generated code, the last increment or decrement of the loop index might cause the index variable to overflow. The index overflow might result in an infinite loop. See Loop Index Overflow (MATLAB Coder).
When the number of
for
-loop iterations calculated by the generated code does not match the number offor
-loop iterations calculated by MATLAB, the generated MEX function produces an error at run time. SeeResolve Error: Cannot Determine the Exact Number of Iterations for a Loop (MATLAB Coder).Do not use
for
loops without static bounds.Do not use the
&
and|
operators within conditions of afor
statement. Instead, use the&&
and||
operators.HDL Coder™ does not support nonscalar expressions in the conditions of
for
statements. Instead, use theall
orany
functions to collapse logical vectors into scalars.
Version History
Introduced before R2006a