while loop for series
Show older comments
im suppose to evaluate the series y=1/m where m is 1 to 5
I can find the different values for y using a while loop statment but cant get it to sum all the values
here is my code so far
clear
m=0
while (m<5)
m=m+1
r=1/m
y=sum(r)
end
what am i doing wrong?
Answers (1)
"what am i doing wrong?"
You are not actually adding anything to y on each iteration, instead you completely overwrite y with a new value, thus making your loop totally superfluous (because you only return the value of the last iteration). In any case a loop is not required:
This is the simple MATLAB way (no loop):
>> m = 1:5;
>> y = sum(1./m)
y = 2.2833
A pointlessly complex looped way:
>> y = 0;
>> for k = m, y = y+1./k; end
>> y
y = 2.2833
Of course you could make that loop even more complex using while.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!