フィルターのクリア

Sum using vectorized commands and colon operator instead of loops.

8 ビュー (過去 30 日間)
David
David 2013 年 10 月 2 日
コメント済み: David 2013 年 10 月 2 日
So, first of all I better say that this isn't a homework assignment. It's a sheet of problems given to us which we can attempt in our own time to help get a feel for the final exam. The problem asks you to compute the sum of 1/(k)^3 from 1 to 1000 without using loops. I can't actually afford MATLAB on my laptop and currently am not in college, so I can't test this code but this is what I came up with off the top of my head:
x = [1:1000]; %creates vector of 1 - 1000
x(1:1000) = 1/(x(1:1000))^3; %replaces each element of that array with the inverse cubed of said %element
a = Sum(x); %Sums up all the values of the new x
disp(a) %displays the value of the sum.
So, does the above code actually make sense of have I gone wrong somewhere? Thanks in advance.

採用された回答

Wayne King
Wayne King 2013 年 10 月 2 日
編集済み: Wayne King 2013 年 10 月 2 日
Yes, it basically makes sense although what you have would not actually work in MATLAB because you need the "dot" operator for element-by-element operations.
And you have some unnecessary code
k = 1:1000;
y = 1./k.^3;
sum(y)
  1 件のコメント
David
David 2013 年 10 月 2 日
Brilliant. Completely forgot about the dot operator. Thanks.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by