for
for
loop to repeat specified number
of times
Syntax
forindex
=values
statements
end
Description
for
executes a group of statements in a loop for a specified
number of times. index
= values
, statements
,
endvalues
has one of the
following forms:
initVal
:
endVal
— Increment theindex
variable frominitVal
toendVal
by1
, and repeat execution ofstatements
untilindex
is greater thanendVal
.initVal
:
step
:
endVal
— Incrementindex
by the valuestep
on each iteration, or decrementsindex
whenstep
is negative.valArray
— Create a column vector,index
, from subsequent columns of arrayvalArray
on each iteration. For example, on the first iteration,
. The loop executes a maximum ofindex
=valArray
(:,1)n
times, wheren
is the number of columns ofvalArray
, given bynumel(
. The inputvalArray
(1,:))valArray
can be of any MATLAB® data type, including a character vector, cell array, or struct.
Examples
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 acontinue
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
Version History
Introduced before R2006a