Skip to content

MATLAB - Nested Loops

MATLAB, like other programming languages, allows you to place one loop inside another. This is known as a nested loop. This structure is useful for iterating over elements in multidimensional arrays or for algorithms that require repeated operations for each step of an outer process.

However, a key skill in writing efficient MATLAB code is knowing when to replace loops with vectorization. This tutorial covers both concepts.

The syntax involves placing one loop construct entirely within another.

for outer_index = 1:m
% Code for the outer loop runs m times
for inner_index = 1:k
% Code for the inner loop runs k times for each outer loop iteration
% Total statements run = m * k times
<statements>;
end
end
while <expression1>
% Outer loop code
while <expression2>
% Inner loop code
<statements>;
end
end

Example: Finding Prime Numbers with a Nested Loop

Section titled “Example: Finding Prime Numbers with a Nested Loop”

Let’s use a nested for loop to find prime numbers. A number is prime if it is only divisible by 1 and itself. Our algorithm will check each number i for factors j from 2 up to the square root of i.

% An improved algorithm to find prime numbers up to 100
max_num = 100;
fprintf('Prime numbers between 1 and %d:\n', max_num);
for i = 2:max_num
is_prime = true; % Assume the number is prime initially
% Inner loop only needs to check for factors up to sqrt(i).
% This is a critical performance optimization.
for j = 2:sqrt(i)
% mod(i, j) == 0 means j is a factor of i.
if mod(i, j) == 0
is_prime = false; % Factor found, so it's not prime
break; % Exit the inner loop early, no need to check further
end
end
if is_prime
fprintf('%d ', i);
end
end
fprintf('\n'); % Print a newline at the end
% Expected Output:
% Prime numbers between 1 and 100:
% 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

The Power of Vectorization: Thinking in Arrays

Section titled “The Power of Vectorization: Thinking in Arrays”

In MATLAB, loops can be slow because each iteration is interpreted. Vectorization is the process of rewriting loop-based, scalar-oriented code to use MATLAB’s matrix and vector operations. Vectorized code is more concise, more readable, and often executes much faster.

Example: From Loop to Vectorized Operation

Section titled “Example: From Loop to Vectorized Operation”

Consider creating a 5x5 multiplication table. A nested loop is the intuitive approach:

% --- Nested Loop Approach (Slow) ---
tic; % Start timer
N = 1000;
mult_table_loop = zeros(N, N);
for row = 1:N
for col = 1:N
mult_table_loop(row, col) = row * col;
end
end
toc; % End timer

The vectorized approach uses array multiplication to achieve the same result in a single line, and it is orders of magnitude faster.

% --- Vectorized Approach (Fast) ---
tic; % Start timer
N = 1000;
col_vector = (1:N)'; % Create a column vector
row_vector = 1:N; % Create a row vector
mult_table_vec = col_vector * row_vector; % Outer product
toc; % End timer
% On a typical machine, the output might be:
% Elapsed time is 0.021567 seconds. (for the loop)
% Elapsed time is 0.000789 seconds. (for the vectorized code)
  • Use Vectorization (Whenever Possible): For operations on all elements of an array, mathematical calculations, logical indexing, and data filtering. Always try to find a vectorized solution first.
  • Use Loops: When the calculation for an element depends on the result of a previous iteration (e.g., iterative solvers, Fibonacci sequence). Also useful when you need to break or continue based on complex conditions that are hard to vectorize.

For many common problems, MATLAB already provides a highly optimized, built-in function. For finding prime numbers, you should use isprime.

max_num = 100;
% Create a vector of numbers to test
numbers = 1:max_num;
% The isprime function returns a logical array (0s and 1s)
prime_flags = isprime(numbers);
% Use logical indexing to select only the prime numbers
primes = numbers(prime_flags)
% Expected Output:
% primes =
% 2 3 5 7 11 13 17 19 ... (and so on)

This demonstrates the ideal MATLAB workflow: think in terms of operations on entire arrays, and leverage built-in functions whenever they are available.