while loop for series
显示 更早的评论
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?
回答(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.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!