Skip to content

MATLAB - Loops

MATLAB - Loop Structures and Best Practices

Section titled “MATLAB - Loop Structures and Best Practices”

In programming, a loop is a control structure that repeats a block of code until a specified condition is met. Loops are essential for automating repetitive tasks, such as processing elements in an array or running iterative algorithms.

The basic control flow of a loop involves a condition check. If the condition is true, the loop body executes, after which the condition is checked again. This continues until the condition becomes false.

MATLAB provides two primary types of loops: for and while.

A for loop executes a block of code a fixed number of times. It iterates over the elements of a vector or matrix, assigning a new value to the loop variable in each iteration.

for loopVariable = range
% Code to be executed
end
% Create a vector of numbers
data = [10, 20, 30, 40, 50];
total = 0; % Initialize accumulator
% Loop through each element in 'data'
for val = data
total = total + val;
end
fprintf('The sum is: %d\n', total);

A while loop repeats a block of code as long as a specified condition remains true. The number of iterations is not predetermined and depends on the condition.

while condition
% Code to be executed
% (Must include code that can change the condition)
end

Example: Find the First Power of 2 Above 1000

Section titled “Example: Find the First Power of 2 Above 1000”
n = 1;
while n < 1000
n = n * 2;
end
fprintf('The first power of 2 greater than 1000 is: %d\n', n);

You can alter the flow of a loop using control statements:

  • break: Immediately terminates the entire loop and execution continues at the statement following the end keyword.
  • continue: Skips the rest of the current iteration and proceeds to the next iteration of the loop.

Critical Best Practice: Vectorization and Pre-allocation

Section titled “Critical Best Practice: Vectorization and Pre-allocation”

While loops are fundamental, overusing them in MATLAB can lead to slow code. MATLAB is optimized for vectorized operations that act on entire arrays at once. Before writing a loop, always consider if a vectorized alternative exists.

Let’s calculate $$y = \sin(x)$$ for 1,000,000 points.

x = linspace(0, 2*pi, 1e6);
% Slow 'for' loop approach
tic; % Start timer
y_loop = zeros(1, 1e6);
for i = 1:length(x)
y_loop(i) = sin(x(i));
end
toc; % End timer
% Fast vectorized approach
tic; % Start timer
y_vec = sin(x);
toc; % End timer
% The vectorized approach is orders of magnitude faster.

If a loop is unavoidable, you must pre-allocate memory for arrays that grow inside the loop. Failing to do so forces MATLAB to resize the array in every iteration, which is extremely inefficient.

% BAD: Growing an array inside a loop
tic;
bad_array = [];
for i = 1:50000
bad_array(i) = i^2;
end
toc;
% GOOD: Pre-allocating memory with zeros()
tic;
good_array = zeros(1, 50000); % Allocate all memory at once
for i = 1:50000
good_array(i) = i^2;
end
toc;
% The pre-allocated approach is significantly faster.