0% found this document useful (0 votes)
4 views

Loops in MATLAB

For loops are counter based loops that allow executing MATLAB statements repeatedly. Examples show using for loops to add elements of a vector, add odd numbers from 1 to 10, and compute the factorial of a user-input number. Nested for loops can print patterns like a triangle of increasing stars specified by the user.

Uploaded by

MadeehaMushtaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Loops in MATLAB

For loops are counter based loops that allow executing MATLAB statements repeatedly. Examples show using for loops to add elements of a vector, add odd numbers from 1 to 10, and compute the factorial of a user-input number. Nested for loops can print patterns like a triangle of increasing stars specified by the user.

Uploaded by

MadeehaMushtaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

For Loops

 For loops are counter based loops

for k=1:1:10
MATLAB statement
end
Example
Following code will add up each element of a vector, and
display the result after ending the for loop.

v = 1:10;
sum = 0;
for i = 1:length(v)
sum = sum + v(i);
end
disp(sum)
Example
We want to add only odd numbers from the numbers in
1:10

sum = 0;
for i = 1:2:10
sum = sum + i;
end
disp(sum)
Example
Write a program to ask a number from a user, verify that the
number is not negative, and compute its factorial.

numb=input('Enter a number: ');


fact=1;
if numb<0
fprintf('the number you have entered is negative');
else
for i=1:numb
fact=fact*i;
end
fact
end
Nested Loops
Let’s say we wanted to print out the following pattern of
stars, allowing the user to specify how many rows:
Example
rows=input(How many rows do you want: ');
for R=1:rows
for s=1:R
fprintf(‘*’);
end
fprintf(‘\n’);
end

You might also like