因此,我目前正在使用"accumarray"来查找与匹配ID相对应的一系列数字的平均值.防爆输入:
So I am currently using 'accumarray' to find the averages of a range of numbers wich correspond to matching ID's. Ex Input:
ID----Value 1 215 1 336 1 123 2 111 2 246 2 851我当前的代码使用ID作为分隔符"来找到上述值的未加权平均值,这样我就不会将所有值的平均值作为一个数字得到,而是将单独的结果仅作为有相应的ID. EX输出:
My current code finds the unweighted average of the above values, using the ID as the 'seperator' so that I don't get the average for all of the values together as one number, but rather seperate results for just values which have corresponding ID's. EX Output:
ID----Value 1 224.66 2 402.66要实现这一点,我正在使用以下代码:
To achieve this I am using this code:
[ID, ~, Groups] = unique(StarData2(:,1),'stable'); app = accumarray(Groups, StarData2(:,2), [], @mean);以StarData2作为函数的输入.到目前为止,这对于我的目的来说是完美的,我需要知道是否可以使accumarray为我提供加权平均值,以便可以为应用程序中的每个点(在找到平均值之前)分配一个权重,或者@mean可以被可以实现这一目标的功能所取代.新的输入将如下所示:
With StarData2 being the input of the function. This is working perfectly for my purposes until now, I need to know if accumarray can be made to give me a weighted average, such that each point in app (before the average is found) can be assigned a weight or that the @mean can be replaced with a function that can achieve this. The new input will look like this:
ID----Value----Weight 1 215 12 1 336 17 1 123 11 2 111 6 2 246 20 2 851 18新代码必须执行sum(val(i)* weight(i))/sum(weight),而不仅仅是标准均值.感谢您的协助.
The new code must do the sum(val(i)*weight(i))/sum(weight) instead of just the standard mean. Thanks for any assistance.
推荐答案您可以将行索引用作"vals"(第二次输入到 accumarray ),然后定义您自己的函数,该函数对数据组进行加权均值:
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)
演示
从data(带有权重的新输入)和unique命令开始:
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');accumarray用法如下(每次更改data时都要重新定义WeightedMeanFcn !)
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更多推荐
MATLAB Accumarray加权平均值
发布评论