2017-01-13 72 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