MATLAB Language For loops

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

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
    display(size(i))
end

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

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


Got any MATLAB Language Question?