Skip to content

MATLAB - For Loop

A for loop is a control flow statement that allows code to be executed repeatedly. It is ideal for situations where you need to iterate a specific number of times, for example, over the elements of an array.

The basic syntax of a for loop in MATLAB is:

for index = values
% Code to be executed in each iteration
% ...
end

The values expression can take several forms:

FormatDescription
start:endIncrements the index variable from start to end by 1 in each iteration.
start:step:endIncrements index by the value step in each iteration. step can be negative to count down.
arrayAssigns successive columns of array to index in each iteration. For a row or column vector, it assigns each element of the vector to index.

This loop iterates from 1 to 5, printing the value of the loop variable k in each step.

for k = 1:5
fprintf('Iteration number: %d\n', k);
end

When you run this code, it displays the following result:

Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5

This loop counts down from 10 to 0 in steps of -2.

for countdown = 10:-2:0
disp(countdown)
end

When you run the file, it displays:

10
8
6
4
2
0

You can directly iterate over the elements of a vector.

data_points = [1.2, 5.5, 2.8, 4.1];
for val = data_points
fprintf('Processing value: %.1f\n', val);
end

The output will be:

Processing value: 1.2
Processing value: 5.5
Processing value: 2.8
Processing value: 4.1

Best Practice: Pre-allocation for Performance

Section titled “Best Practice: Pre-allocation for Performance”

A common use for for loops is to build an array or matrix. However, repeatedly resizing an array inside a loop (e.g., by appending elements) is very slow in MATLAB. The best practice is to pre-allocate memory for the array before the loop starts.

tic; % Start timer
results = []; % Initialize an empty array
for i = 1:100000
results(i) = i^2; % Array grows in every iteration
end
toc; % Stop timer
% Elapsed time is significantly longer.
tic; % Start timer
num_elements = 100000;
results = zeros(1, num_elements); % Pre-allocate memory
for i = 1:num_elements
results(i) = i^2; % Fill in the pre-allocated values
end
toc; % Stop timer
% Elapsed time is much shorter.

Vectorization: The Alternative to for Loops

Section titled “Vectorization: The Alternative to for Loops”

While for loops are necessary, many tasks in MATLAB can be performed more efficiently using vectorization. This means applying operations to entire arrays at once, rather than element by element. If you can express a computation as a vectorized operation, it will almost always be faster than a loop.

% Goal: Square every element in a vector
% Using a for loop (slower)
x = 1:1000;
y = zeros(size(x));
for i = 1:length(x)
y(i) = x(i)^2;
end
% Using vectorization (faster and cleaner)
x = 1:1000;
y_vectorized = x.^2; % The .^ operator performs element-wise power
% Both y and y_vectorized contain the same result.

Always look for a vectorized solution before writing a for loop. Loops are best reserved for procedures that are inherently sequential and cannot be vectorized.