for loop
Loops are used to perform the same set of statements multiple times. The for loop runs the statements a set number of times based on the number of elements in the collection found on the first line of the for loop.
for loopVar=collection
blockFor
end
A for loop is executed a discrete number of times based on the number of elements in the collection. The loopVar is set to the first element of collection and the statements in blockFor are executed. Then, loopVar is set to the next element of collection, the statements in blockFor are executed, and the process repeats until collection is exhausted.
Modifying loopVar inside blockFor will not change the
loop execution (in other words, you cannot exit the loop early by changing the value of
loopVar).
for j =1:3
disp(j)
j = j+5
end
Results in:
1
j = 6
2
j=7
3
j = 8
The final value of the
loop variable is retained after the loop is completed. In many cases, the collection is created at the time the loop is executed using the :
operator.
for j=1:10
disp(a(j))
end