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.
The for Loop
Section titled “The for Loop”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.
Syntax
Section titled “Syntax”for loopVariable = range % Code to be executedendExample: Summing Array Elements
Section titled “Example: Summing Array Elements”% Create a vector of numbersdata = [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);The while Loop
Section titled “The while Loop”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.
Syntax
Section titled “Syntax”while condition % Code to be executed % (Must include code that can change the condition)endExample: 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);Loop Control Statements
Section titled “Loop Control Statements”You can alter the flow of a loop using control statements:
break: Immediately terminates the entire loop and execution continues at the statement following theendkeyword.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.
Vectorization Example
Section titled “Vectorization Example”Let’s calculate $$y = \sin(x)$$ for 1,000,000 points.
x = linspace(0, 2*pi, 1e6);
% Slow 'for' loop approachtic; % Start timery_loop = zeros(1, 1e6);for i = 1:length(x) y_loop(i) = sin(x(i));endtoc; % End timer
% Fast vectorized approachtic; % Start timery_vec = sin(x);toc; % End timer
% The vectorized approach is orders of magnitude faster.Pre-allocation Example
Section titled “Pre-allocation Example”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 looptic;bad_array = [];for i = 1:50000 bad_array(i) = i^2;endtoc;
% GOOD: Pre-allocating memory with zeros()tic;good_array = zeros(1, 50000); % Allocate all memory at oncefor i = 1:50000 good_array(i) = i^2;endtoc;
% The pre-allocated approach is significantly faster.