What's wrong with my code? (Beginner's question; geometric sum)

This is the sum I'm trying to use:
1 + r^2 + r^4 + r^6 + ... + r^n
If n isn't even, I'm supposed to display an error.
Here's my code:
function [sum] = series(r,n)
sum = 1;
if mod(n,2) == 0
for i=2:n
sum = sum + r.^i;
end
else
disp('Error!');
end
end
Keeps returning the wrong value. What's wrong with my code?

 採用された回答

Roger Stafford
Roger Stafford 2014 年 11 月 13 日
編集済み: Roger Stafford 2014 年 11 月 13 日

1 投票

Replace
for i=2:n
by
for i=2:2:n
Or you could always just write
(1-r^(n+2))/1-r^2)
for even n.

2 件のコメント

n
n 2014 年 11 月 13 日
Thank you!
Image Analyst
Image Analyst 2014 年 11 月 13 日
Here is the question Roger answered so people will know after n deletes his question, which he has a bad habit of doing:
This is the sum I'm trying to use:
1 + r^2 + r^4 + r^6 + ... + r^n
If n isn't even, I'm supposed to display an error.
Here's my code:
function [sum] = series(r,n)
sum = 1;
if mod(n,2) == 0
for i=2:n
sum = sum + r.^i;
end
else
disp('Error!');
end
end
Keeps returning the wrong value. What's wrong with my code?

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2014 年 11 月 13 日

0 投票

Don't use sum as the name of a variable since it's a built-in function. You want
for k = 2 : 2 : n
theSum = theSum + r^k;

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

タグが未入力です。

質問済み:

n
n
2014 年 11 月 13 日

コメント済み:

2014 年 11 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by