How to Use For Loop in MATLAB: Syntax and Examples
In MATLAB, use a
for loop to repeat a block of code a fixed number of times. The syntax is for variable = startValue:endValue, followed by the code to repeat, and closed with end. This lets you run commands repeatedly with changing values.Syntax
The basic syntax of a for loop in MATLAB is:
for variable = startValue:endValue: This sets the loop variable to startValue and increases it by 1 each time until it reaches endValue.- The code inside the loop runs once for each value of the variable.
endmarks the end of the loop block.
matlab
for i = 1:5 % Code to repeat end
Example
This example prints numbers from 1 to 5 using a for loop. It shows how the loop variable changes each time and how the code inside runs repeatedly.
matlab
for i = 1:5 disp(i) end
Output
1
2
3
4
5
Common Pitfalls
Common mistakes when using for loops in MATLAB include:
- Forgetting the
endkeyword to close the loop. - Using a loop variable that conflicts with existing variables.
- Assuming the loop variable changes inside the loop without explicitly modifying it.
- Using non-integer or empty ranges which can cause unexpected behavior.
matlab
%% Wrong: Missing end for i = 1:3 disp(i) % Missing end causes error %% Correct: for i = 1:3 disp(i) end
Output
1
2
3
Quick Reference
| Part | Description |
|---|---|
| for variable = start:end | Starts the loop with variable from start to end |
| Code inside loop | Runs once per loop iteration |
| end | Ends the loop block |
| Variable | Loop counter that changes each iteration |
| Range | Defines how many times the loop runs |
Key Takeaways
Use
for variable = start:end to repeat code a fixed number of times in MATLAB.Always close your
for loop with end to avoid errors.The loop variable changes automatically each iteration from start to end values.
Avoid using conflicting variable names inside loops to prevent bugs.
Check your loop range to ensure it is valid and produces the expected number of iterations.