BudiBadu Logo
Samplebadu

MATLAB by Example: Loops

R2023b

Loops allow you to repeat code. This example shows `for` loops iterating over vectors and `while` loops.

Code

% For loop
% Iterates 5 times
for i = 1:5
    fprintf('Iteration: %d\n', i);
end

% Nested loop
for i = 1:3
    for j = 1:3
        A(i, j) = i + j;
    end
end

% While loop
count = 0;
while count < 5
    count = count + 1;
end

% Vectorization is often preferred over loops!
% Instead of:
% for i = 1:length(x)
%    y(i) = x(i)^2;
% end
% Use:
% y = x.^2;

Explanation

MATLAB supports standard control flow structures like for and while loops. A for loop typically iterates over a vector of values created by the colon operator, such as for i = 1:10. The loop variable i takes on each value in the vector sequentially. The loop block is terminated with the end keyword.

The while loop continues to execute as long as the specified condition remains true. It is useful when you don't know the number of iterations in advance, such as when waiting for convergence in a numerical algorithm. You must ensure the condition eventually becomes false to avoid infinite loops.

While loops are available, experienced MATLAB users often avoid them in favor of "vectorization". Vectorization involves rewriting loop-based code to use matrix and vector operations. This takes advantage of MATLAB's highly optimized underlying linear algebra libraries, often resulting in code that runs significantly faster and is more concise.

Code Breakdown

3
for i = 1:5 sets up the loop. i will be 1, 2, 3, 4, 5 in each pass.
27
y = x.^2 is the vectorized equivalent of squaring each element in a loop.