A for loop can have any increment. Even a vector of numbers can be the increment. And it need not be in any order. Some examples:
for n = 1:10
stuff
end
for n = 2:2:12
stuff
end
P = primes(100);
for n = P
stuff
end
nvals = [1 10 100 1000 10000 100000];
for n = nvals
stuff
end
nvals = [2 1 5 14 pi -1000 1 3 1.273435345 2+3i];
for n = nvals
disp(n)
end
2
1
5
14
3.14159265358979
-1000
1
3
1.273435345
2 + 3i
nvals = {1 pi,'bcde'};
for n = nvals
disp(n)
end
[1]
[3.14159265358979]
'bcde'
nvals = 'The quick brown fox jumped over the lazy dog'
for n = nvals
disp(n)
end
T
h
e
q
u
i
c
k
b
r
o
w
n
f
o
x
j
u
m
p
e
d
o
v
e
r
t
h
e
l
a
z
y
d
o
g
In a few cases, I've reported the value of n at each step through the loop. As you can see, the elements of the row vector may be any number. It can be of class uint8 or double, or even a cell vector.
Be careful of one thing however. The for statement operates as you would expect ONLY when given a ROW vector. It iterates across the COLUMNS of the input. So if the argument to for is a COLUMN vector, then the for loop runs for only one step. If it is a matrix, then the result will be a sequence of vectors!
nvals = magic(3)
nvals =
8 1 6
3 5 7
4 9 2
for n = nvals
disp('A column')
disp(n)
end
A column
8
3
4
A column
1
5
9
A column
6
7
2
Best Answer