0
0
MatlabHow-ToBeginner ยท 3 min read

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.
  • end marks 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 end keyword 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

PartDescription
for variable = start:endStarts the loop with variable from start to end
Code inside loopRuns once per loop iteration
endEnds the loop block
VariableLoop counter that changes each iteration
RangeDefines 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.