How to find the partial sum of the series using while loop?
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Teb Keb
el 13 de Feb. de 2022
Comentada: Teb Keb
el 13 de Feb. de 2022
I need to find the partial sum of the series S=1/n for n=5 using while loop.
n = 1 ;
s = 0 ;
while n<=5;
s = s+1/n ;
end
s
I tried using this code I have but matlab won't run. I am not sure what i am doing wrong.
0 comentarios
Respuesta aceptada
DGM
el 13 de Feb. de 2022
Editada: DGM
el 13 de Feb. de 2022
Using a while loop when the number of iterations is known is an unnecessary invitation for mistakes like that. You weren't incrementing n, so the loop would never exit. Just use a for-loop if you must use a loop.
s = 0 ;
for n = 1:5
s = s+1/n ;
end
s
If you don't need to use a loop, then things can be simplified.
s = sum(1./(1:5))
3 comentarios
DGM
el 13 de Feb. de 2022
s = 0 ;
n = 1;
while n<=5
s = s+1/n ;
n = n+1; % increment
end
s
Más respuestas (1)
Image Analyst
el 13 de Feb. de 2022
To get the partial sums (sums that depend on what element you're at), you can use cumsum()
n = 1 : 5;
s = cumsum(1 ./ n)
This is the "vectorized" way of doing it that most MATLAB programmers would use. s(end) is the final/last sum for all 5 elements. Or in the while loop
s = 0 ;
n = 1;
while n <= 5
s(n) = s(end) + 1 / n ;
n = n + 1; % Increment n
end
s(end)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!