You are on page 1of 8

MATLAB

Lecture 4
Loops

For Loops -1

While Loops -2
Loops>> For Loops
To repeat a statement or a group of statements for a fixed
.number of times

Sequential numbers Non-Sequential numbers


Loops>> For Loops
Loops>> For Loops
Ex: Getting the sum of matrix element:
x = [7 0 9 4 3];
y = 0;
for i=1:length(x)
y = y+x(i);
end

Alternate way using MATLAB's built-in vector and matrix operations


instead of explicit loops.
% Do add up all the elements of x, use this:
y = sum(x)
% which is better than the previous way
Loops>> For Loops
Exercises :
•Print numbers from 1:10
for i=1:10
disp(i)
end
•Print the multiples of 3 from 3 up to 300
for i=3:3:300
disp(i);
end
•Print the multiples of 3 from 300 down to 3
for i=300:-3:3
disp(i);
end

• Get the Factorial 10! = 10*9*8*…………..*2*1


f=1
for i=1:10
f=f*i
end
f
Loops>> Nested For Loops
i =
1
j =
for i=1:3 10
i j =
for j = 10:10:30 20
j j =
30
end
= i
end 2
j =
10
j =
20
j =
30
i =
3
j =
10
j =
20
j =
30
Loops>> Nested For Loops
• Print a sequence of asterisk characters in the following configuration
*
**
***
****
*****
******
*******
********
for i=1: 8
for j=1:i
fprintf ('*');
end
fprintf ('\n');
end

• Print a sequence of asterisk characters in the following configuration


*
*
*
*
*
*
*
*
for i=1: 8
for j=1:i
fprintf (' ');
end
fprintf ('* \n');
end

You might also like