How to find the partial sum of the series using while loop?

조회 수: 10 (최근 30일)
Teb Keb
Teb Keb 2022년 2월 13일
댓글: Teb Keb 2022년 2월 13일
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.

채택된 답변

DGM
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
s = 2.2833
If you don't need to use a loop, then things can be simplified.
s = sum(1./(1:5))
s = 2.2833
  댓글 수: 3
DGM
DGM 2022년 2월 13일
s = 0 ;
n = 1;
while n<=5
s = s+1/n ;
n = n+1; % increment
end
s
s = 2.2833
Teb Keb
Teb Keb 2022년 2월 13일
oh wow. thank you so much!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
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)
s = 1×5
1.0000 1.5000 1.8333 2.0833 2.2833
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)
ans = 2.2833

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by