A common source of bugs is trying to loop over the elements of a column vector. A column vector is treated like a matrix with one column. (There is actually no distinction in Matlab.) The for
loop runs once with the loop variable set to the column.
% Prints once: [3, 1]
my_vector = [1; 2; 3];
for i = my_vector
display(size(i))
end
Altering the iteration variable changes its value for the current iteration, but has no impact on its value in subsequent iterations.
% Prints 1, 2, 3, 4, 5
for i = 1:5
display(i)
i = 5; % Fail at trying to terminate the loop
end
a:b
in right-hand sideThe basic example treats 1:n
as a normal instance of creating a row vector and then iterating over it. For performance reasons, Matlab actually treats any a:b
or a:c:b
specially by not creating the row vector entirely, but instead creating each element one at a time.
This can be detected by slightly altering the syntax.
% Loops forever
for i = 1:1e50
end
% Crashes immediately
for i = [1:1e50]
end