MATLAB - For Loop
MATLAB - The for Loop
Section titled “MATLAB - The 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.
Syntax
Section titled “Syntax”The basic syntax of a for loop in MATLAB is:
for index = values % Code to be executed in each iteration % ...endThe values expression can take several forms:
| Format | Description |
|---|---|
start:end | Increments the index variable from start to end by 1 in each iteration. |
start:step:end | Increments index by the value step in each iteration. step can be negative to count down. |
array | Assigns successive columns of array to index in each iteration. For a row or column vector, it assigns each element of the vector to index. |
Example 1: Simple Iteration
Section titled “Example 1: Simple Iteration”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);endWhen you run this code, it displays the following result:
Iteration number: 1Iteration number: 2Iteration number: 3Iteration number: 4Iteration number: 5Example 2: Iterating with a Custom Step
Section titled “Example 2: Iterating with a Custom Step”This loop counts down from 10 to 0 in steps of -2.
for countdown = 10:-2:0 disp(countdown)endWhen you run the file, it displays:
10
8
6
4
2
0Example 3: Iterating Over an Array
Section titled “Example 3: Iterating Over an Array”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);endThe output will be:
Processing value: 1.2Processing value: 5.5Processing value: 2.8Processing value: 4.1Best 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.
Inefficient Code (Avoid This)
Section titled “Inefficient Code (Avoid This)”tic; % Start timerresults = []; % Initialize an empty arrayfor i = 1:100000 results(i) = i^2; % Array grows in every iterationendtoc; % Stop timer% Elapsed time is significantly longer.Efficient Code (Best Practice)
Section titled “Efficient Code (Best Practice)”tic; % Start timernum_elements = 100000;results = zeros(1, num_elements); % Pre-allocate memoryfor i = 1:num_elements results(i) = i^2; % Fill in the pre-allocated valuesendtoc; % 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.