MATLAB - Nested Loops
MATLAB - Nested Loops and Vectorization
Section titled “MATLAB - Nested Loops and Vectorization”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.
Syntax of Nested Loops
Section titled “Syntax of Nested Loops”The syntax involves placing one loop construct entirely within another.
Nested for loop:
Section titled “Nested for loop:”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
endNested while loop:
Section titled “Nested while loop:”while <expression1> % Outer loop code
while <expression2> % Inner loop code <statements>; end
endExample: 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 100max_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); endendfprintf('\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 97The 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 timerN = 1000;mult_table_loop = zeros(N, N);for row = 1:N for col = 1:N mult_table_loop(row, col) = row * col; endendtoc; % End timerThe 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 timerN = 1000;col_vector = (1:N)'; % Create a column vectorrow_vector = 1:N; % Create a row vectormult_table_vec = col_vector * row_vector; % Outer producttoc; % 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)When to Use Loops vs. Vectorization
Section titled “When to Use Loops vs. Vectorization”- 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
breakorcontinuebased on complex conditions that are hard to vectorize.
The Prime Number Problem, Vectorized
Section titled “The Prime Number Problem, Vectorized”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 testnumbers = 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 numbersprimes = 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.