# for loop in MATLAB (With Examples)

for loop is a very useful command that allows you to repeat a block of code. A for loop specifically repeats for a pre-set number of iterations. You must know the number of passes that the loop will make beforehand.

This tutorial will demonstrate the basic layout of a for loop and 4 examples of its use, all using the version MATLAB R2022a.

# The for loop

A for loop is generally written as:

``````for variable= m:s:n

statement(s);

end``````

Where:

• variable tells us how many times the for loop will repeat
• The vector m:s:n is the vector that we are performing the for loop on.
m is the initial value
s is the step value (the value that each iteration will increase by)
n is final or terminating value.
• statement(s) is where you will write any code (such as displaying the output).  You can remove the semicolon after statement(s) to show each iteration in the command window.

The way in which you use a for loop is best illustrated with examples.

## How to write a basic for loop

``````for i=1:1:4
i
end
``````

This will iterate by 1 at a time through the 4 values of i and output i = 4.

The first line means: i = initial value: increment steps: final value.

This is basic form of the for loop.

## How to display values of a vector

``````x = -5:5;

for i = 1:length(x)

x(i)

end``````

This iterates through the vector x using the index i up to the length of the vector x (which in this case will be 11).

## How to use an array in a for loop

In MATLAB, this is an example of what an array is written as

``[4 10 16 20 24]``

let us call our array x

Then

``````x = [4 10 16 20 24]

for i = 1:1:length(x);

y(i) = 3*x(i)

end``````

This will go through each iteration changing that part of the array until the final output is also an array.

## How to nest other conditionals in the for loop

A for loop can also contain other conditional statements such as: if, elseif and else.

``````x = -5:1:10;

for i = 1:1:length(x)

if x(i)<0

y(i) = 0;

elseif x(i)<5

y(i) = x(i)^2 +3;

else  y(i) = 2*x(i);

end

end``````

Note: Make sure each logic statement is ended with the end function.

Here we have an example that is best to illustrate by plotting the function. This guide shows you how to plot functions in MATLAB if you do not know how to do so.

To plot this one we just use these commands:

``````plot(x,y)

xlabel('x')

ylabel('y')

title('Plot of y(x)')
``````