MATLAB Language For loops


Iterate over column vector

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

Altering the iteration variable

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
    i = 5; % Fail at trying to terminate the loop

Special case performance of a:b in right-hand side

The 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
% Crashes immediately
for i = [1:1e50]