How to make a sum series using a for loop

48 ビュー (過去 30 日間)
Petch Anuwutthinawin
Petch Anuwutthinawin 2021 年 6 月 11 日
回答済み: Geoff Hayes 2021 年 6 月 11 日
Given the power series of sin(x) I have to create a function that takes in x vector and N (number of terms in the sequence) and outputs the power series approximation of pi at that N. I cannot use any trig command or any sum command in the answer. I have written this code so far, which says that the sum= the first term (which would be x) plus the k'th term in the sequence. My problem is that MatLab keeps printing out the x value as the answer instead of the sum. How can I fix this code to make it so that MatLab prints out the sum.
for k=1:N
s=x+((-1)^k)*((x^(2*k+1))/factorial(2*k+1));
end

採用された回答

Geoff Hayes
Geoff Hayes 2021 年 6 月 11 日
Petch - in your code, you are assigning the kth iteration value (plus x) to s rather than summing all values. Try instead
s = x;
for k=1:N
s = s + ((-1)^k)*((x^(2*k+1))/factorial(2*k+1));
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by