Matlab : Looping

This chapter will cover the use of common syntax for looping in MATLAB such as for and while.


For Loop

This is an example how to use “for” loop in MATLAB. We define the number iteration as n = 3 and update the value of f = 1 in each iteration with f * i where i is the iteration index. The value of f from each iteration will be displayed in the command window with disp() function.

Syntax :

n = 3;

f = 1;

for i = 1:n

f = f * i;

disp(f)

end

Result :

>>

1

2

6


While Loop

This is an example how to write “while” loop in MATLAB. From this example, we set i as 3 and decrease its value as long its larger than 0. The disp() function will show the updated value of i along time.

Syntax :

% while loop

i = 3;

while (i>0)

disp(i)

i = i – 1;

end

Result:

>>
3

2

1