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?

Antworten (1)

Stephen23
Stephen23 am 28 Sep. 2019
Bearbeitet: Stephen23 am 28 Sep. 2019

0 Stimmen

"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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 28 Sep. 2019

Bearbeitet:

am 28 Sep. 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by