The right-hand side of the assignment in a for
loop can be any row vector. The left-hand side of the assignment can be any valid variable name. The for
loop assigns a different element of this vector to the variable each run.
other_row_vector = [4, 3, 5, 1, 2];
for any_name = other_row_vector
display(any_name)
end
The output would display
4
3
5
1
2
(The 1:n
version is a normal case of this, because in Matlab 1:n
is just syntax for constructing a row vector of [1, 2, ..., n]
.)
Hence, the two following blocks of code are identical:
A = [1 2 3 4 5];
for x = A
disp(x);
end
and
for x = 1:5
disp(x);
end
And the following are identical as well:
A = [1 3 5 7 9];
for x = A
disp(x);
end
and
for x = 1:2:9
disp(x);
end
Any row vector will do. They don't have to be numbers.
my_characters = 'abcde';
for my_char = my_characters
disp(my_char)
end
will output
a
b
c
d
e