

Essentials of the For Loop in MATLAB
Basic syntax and typical applications
The for loop is one of the most commonly used control structures in MATLAB programming. Mastering it can help you efficiently handle various repetitive tasks. This article will quickly guide you through its usage and typical application scenarios.

Today’s Knowledge Point: Loop Structure (For Loop)


The for loop is a structure in MATLAB used to repeatedly execute a block of code, suitable for situations where the number of iterations is known.


Syntax format: for index = start:step:end% Loop body code% In each iteration, the value of index changes from start to end by the increment of stepend


– start is the starting value, step is the value by which index increases in each iteration (default is 1, can be omitted), end is the terminating value.


– The code in the loop body will be executed repeatedly according to the value of index.
Example Code


% Calculate the sum of integers from 1 to 10
sum_value = 0;
for i = 1:10
sum_value = sum_value + i;
end
disp(['The sum of integers from 1 to 10 is: ', num2str(sum_value)]);


% Print multiplication table
for i = 1:9
for j = 1:9
result = i * j;
fprintf(‘%d x %d = %d\n’, i, j, result);
end
fprintf(‘\n’);
end


In the first example, the for loop iterates from 1 to 10, adding the value of i to sum_value each time, ultimately obtaining the sum of integers from 1 to 10.


The second example demonstrates nested for loops, where the outer loop controls the number of rows and the inner loop controls the number of columns, used for printing a multiplication table.
Application Scenarios

1. Numerical calculations: For example, calculating the sum or average of a sequence. For instance, calculating the sum of squares of the first n terms of a sequence.


2. Data processing: Iterating through each element in a matrix or vector for operations, such as applying a mathematical transformation to each element of a matrix.


3. Iterative algorithms: Many iterative algorithms, such as Newton’s method for finding roots of equations, rely on for loops to control the number of iterations.
Quiz

1. Write a piece of for loop code to calculate and output the factorial of numbers from 1 to 5 (n! = n (n – 1) … * 1).
2. Assume there is a vector v = [10, 20, 30, 40, 50], use a for loop to multiply each element in the vector by 2 and output the resulting vector.

3. Use a for loop to create a 5×5 matrix, where the diagonal elements are 1 and the rest are 0.


(Answers from the previous day’s quiz: 1. eye(3) or [1 0 0; 0 1 0; 0 0 1]; 2. 4; 3. B(:, 2) )
END
