You can use the row index as the "vals" (second input to accumarray
) and define your own function that does the weighted mean on group of the data:
Weights = data(:,3); Vals = data(:,2); % pick your columns here
WeightedMeanFcn = @(ii) sum(Vals(ii).*Weights(ii))/sum(Weights(ii));
wmeans = accumarray(Groups, 1:numel(Groups), [], WeightedMeanFcn)
Demonstration
Starting with data
(the new input with your weights) and your unique
command:
data = [1,215,12; 1,336,17; 1,123,11; 2,111,6; 2,246,20; 2,851,18];
[ID, ~, Groups] = unique(data(:,1),'stable');
The accumarray
usage is as follows (redefine WeightedMeanFcn
every time you change data
!):
>> Weights = data(:,3); Vals = data(:,2); % pick your columns here
>> WeightedMeanFcn = @(ii) sum(Vals(ii).*Weights(ii))/sum(Weights(ii));
>> app = accumarray(Groups, 1:numel(Groups), [], WeightedMeanFcn)
app =
241.1250
475.0909
Checking manually, with the first group:
ig = 1;
sum(data(Groups==ig,2).*data(Groups==ig,3))/sum(data(Groups==ig,3))
ans =
241.1250
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…