2017-01-13 70 views
1

accumarray在Matlab中是惊人的,我经常使用它。我有一个问题,我想传递给accumarray的函数是加权平均值。即它采用两个向量,而不是单个向量。这似乎是accumarray不支持的用例。使用accumarray进行加权平均?

我的理解是否正确?

考虑,功能weightedAverage

function [ result ] = weightedMean(values, weights) 

result = sum(values(:).*weights(:))/sum(weights(:)); 

end 

现在,我们要运行accumarray如下:

subs = [1 1 1 2 2 3 3 3]; 
vals = [1 2 3 4 5 6 6 7]; 
weights = [3 2 1 9 1 9 9 9]; 

accumarray(subs, [vals;weights],[], @weightedMean) 

但MATLAB的回报:

Error using accumarray 
Second input VAL must be a vector with one element for each row in SUBS, or a scalar. 
+0

我不知道。你能举一个例子吗?也许你试过的代码? – beaker

回答

1

你是正确的,第二输入必须是或者列向量或标量。您可以传递一系列索引,而不是将您的数据传递给accumarray,然后您可以使用索引数组将索引编入您的valuesweights向量中,并从计算加权平均值的匿名函数中进行索引。

inds = [1 1 2 2 3 3].'; 
values = [1 2 3 4 5 6]; 
weights = [1 2 1 2 1 2]; 

output = accumarray(inds(:), (1:numel(inds)).', [], ... 
        @(x)sum(values(x) .* weights(x) ./ sum(weights(x)))) 
% 1.6667 
% 3.6667 
% 5.6667