0
0
MATLABdata~5 mins

For loops in MATLAB

Choose your learning style9 modes available
Introduction

For loops help you repeat a set of actions many times without writing the same code again and again.

When you want to add numbers from 1 to 10.
When you want to print each item in a list one by one.
When you want to perform the same calculation on many values.
When you want to create a pattern by repeating steps.
When you want to process rows in a table or matrix.
Syntax
MATLAB
for index = startValue:endValue
    % commands to repeat
end
The index changes from startValue to endValue, one step at a time.
The commands inside the loop run once for each value of index.
Examples
This prints numbers 1 to 5, one number per line.
MATLAB
for i = 1:5
    disp(i)
end
This counts down from 10 to 2 by steps of 2 and prints each number.
MATLAB
for x = 10:-2:2
    disp(x)
end
This prints each letter in the array one by one.
MATLAB
for letter = ['a', 'b', 'c']
    disp(letter)
end
Sample Program

This program adds numbers from 1 to 5 using a for loop and then prints the total.

MATLAB
sum = 0;
for n = 1:5
    sum = sum + n;
end
fprintf('Sum of numbers 1 to 5 is %d\n', sum);
OutputSuccess
Important Notes

Remember to end the loop with end in MATLAB.

You can use any variable name for the loop index, not just i.

The step size in the loop can be changed by adding a third number in the range, like 1:2:9.

Summary

For loops repeat commands for a set number of times.

The loop index changes each time to control repetition.

Use end to close the loop block.