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