Loops in MATLAB
Loops in MATLAB
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.