フィルターのクリア

finding a sum of a vector without using the sum(x) function

3 ビュー (過去 30 日間)
SonOfAFather
SonOfAFather 2012 年 9 月 12 日
I can make my program give the correct answer using the sum(x) function, but i can't use the sum(x) function. is there a way to use either a for or while loop to accomplish the same thing. my present code is:
clc;
clear all;
close all;
w = [1,1.2,.8,1];
x = [75, 80, 65, 78];
wa = 75;
for i = 1:1:length(x);
wa(i) = x(i)*w(i);
end
sum(wa(1:i)./i)
this yeilds the 75.25 answer that i should get. is there some simple that will fix the sum(wa(1:i)./i) I know that i can use the finite fix of wa(1)+wa(2)+...+wa(i), but i need it to work for any number of indexis of wa. as sum(wa(1:i)) does.

採用された回答

Sean de Wolski
Sean de Wolski 2012 年 9 月 12 日
編集済み: Sean de Wolski 2012 年 9 月 12 日
Okay code golf:
w*x'/numel(x)
  1 件のコメント
Matt Fig
Matt Fig 2012 年 9 月 12 日
編集済み: Matt Fig 2012 年 9 月 12 日
Hole-in-one.
ans/length(x)

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

その他の回答 (1 件)

Matt Fig
Matt Fig 2012 年 9 月 12 日
If you don't need all of the wa, you should just do a running sum.
w = [1,1.2,.8,1];
x = [75, 80, 65, 78];
wa = 0;
for ii = 1:1:length(x);
wa = wa + x(ii)*w(ii);
end
wa/ii

カテゴリ

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