フィルターのクリア

Cannot get factorial loop to work! Do not know command...

1 回表示 (過去 30 日間)
S
S 2014 年 2 月 9 日
回答済み: Roger Stafford 2014 年 2 月 9 日
The question is evaluate the following series: 1^2 + 2^2 +3^2 ... + 100^2. The answer is suppose to be 338350 but the only code i can get working is
a=[1:100] b=2; y=a.^b for y=1:length(a) end
which gives me each columns value, but does not add it up to value 338350! I have tried everything for a whole week please help :(

回答 (2 件)

Mischa Kim
Mischa Kim 2014 年 2 月 9 日
編集済み: Mischa Kim 2014 年 2 月 9 日
Use
a = [1:100];
b = 2;
y = 0;
for ii = 1:length(a)
y = y + a(ii)^b;
end
display(y);
Your sum, y, needs to be inside the loop to be updated. Alternatively, you can make use of MATLAB's matrix operations
y = sum([1:100].^2);
  3 件のコメント
John D'Errico
John D'Errico 2014 年 2 月 9 日
編集済み: John D'Errico 2014 年 2 月 9 日
Noe that the internal brackets [] are slightly bad, in the sense that they may make your code slightly less efficient. Use () there instead, so
y = sum((1:100).^2);
is better. Not a major issue, but one to remember. If you don't really need brackets, which will result in an extra function call overhead that was never needed, don't use them. Use parens instead. I'm pretty sure that mlint flags this issue.
John D'Errico
John D'Errico 2014 年 2 月 9 日
Another option here would be
y = dot(1:100,1:100);

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


Roger Stafford
Roger Stafford 2014 年 2 月 9 日
Yet another way is:
n = 100;
y = n*(n+1)*(2*n+1)/6;

カテゴリ

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