How to find the partial sum of the series using while loop?
10 次查看(过去 30 天)
显示 更早的评论
采纳的回答
DGM
2022-2-13
编辑:DGM
2022-2-13
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))
更多回答(1 个)
Image Analyst
2022-2-13
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)
另请参阅
类别
在 Help Center 和 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!