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!