MATLAB Loop

After reading this MATLAB Loop topic, you will understand loop types and you will know the for and while loops theory, and examples.

In real life, many times we need to perform some task repeated over and over, until a specific goal is reached. That’s why MATLAB provides us, a repetitive structure called loop.

MATLAB loops are generally used for executing the block of statements repeatedly along with tracking of each iteration with an incrementing index variable. MATLAB loops are classified as are: –

  • for
  • while

MATLAB – for Loop

MATLAB for loop executes statements a specific number of times.

General Form:

for variable = initial value : final value
   statements
   .
   .
   .
end

MATLAB for loop executes statements a specific number of times.
MATLAB for loop first initialize the variable with the initial value then execute statements after that increment the variable value by 1 and do this again and again until the variable value reaches to the final value.

Examples:

Program (1): To print number 5 two times.

for k=1:2
disp(5)
end
MATLAB VIEW – Program (1):

Create a script file in MATLAB and type the following code  –

Output (1):

5
5
MATLAB VIEW – Output (1):

Program (2): To print a table of any number, enter by user.

r=input('enter number = ');
for n=1:10
n=n*r;
disp(n)
end
MATLAB VIEW – Program (2):

Create a script file in MATLAB and type the following code  –

Output (2):

enter number = 10

10
20
30
40
50
60
70
80
90
100
MATLAB VIEW – Output (2):

Matlab – while Loop

General Form:

while expression(1)
statements
end

MATLAB while loop executes statements repeatedly an indefinite number of times as long as expression(1) evaluates to true condition.

Example:

Program (1): To print number 2 four times.

d=0;
while d<4
disp(2)
d=d+1;
end
MATLAB VIEW – Program (1):

Create a script file in MATLAB and type the following code  –

Output (1):

2
2
2
2
MATLAB VIEW – Output (1):

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top