MATLAB 查找并将函数应用于重复索引的值 [英] MATLAB find and apply function to values of repeated indices
问题描述
我有一个 352x11 的矩阵,由第 1 列索引,有 10 个数据点.一些索引值是重复的.我想找到重复的索引并计算重复试验的平均数据点(如果可能,避免循环).
I have a 352x11 matrix, indexed by column 1 with 10 data points. Some of the index values are repeated. I'd like to find the repeated indices and calculate the mean data points for the repeated trials (avoiding loops, if possible).
例如
x =
26 77.5700 17.9735 32.7200
27 40.5887 16.6100 31.5800
28 60.4734 18.5397 33.6200
28 35.6484 27.2000 54.8000
29 95.3448 19.0000 37.7300
30 82.7273 30.4394 39.1400
结束:
ans =
26 77.5700 17.9735 32.7200
27 40.5887 16.6100 31.5800
28 48.0609 22.8699 44.2150
29 95.3448 19.0000 37.7300
30 82.7273 30.4394 39.1400
我在想如果我用过
J = find(diff(x(:,1))==0);
为了找到重复值的位置,然后我可以将函数应用到x
的对应位置,但是我从哪里开始呢?
to find the position of the repeated values, I could then apply the function to the corresponding positions of x
, but where do I begin?
推荐答案
您可以将 accumarray
应用到多列 如下所示
You can apply accumarray
to multiple columns as shown here
labels = x(:,1) - min(x(:, 1)) + 1;
labels = [repmat(labels(:),size(x,2),1), kron(1:size(x,2),ones(1,numel(labels))).'];
totals = accumarray(labels,x(:),[], @mean);
这是改编自 Gnovice 的代码.
为了让它适用于您的代码,您需要删除前面的所有零
To get it to work for your code you then need to delete all the zeros in the front
totals(find(mean((totals == zeros(size(totals)))')), :) = [];
结果是想要的
26.0000 77.5700 17.9735 32.7200
27.0000 40.5887 16.6100 31.5800
28.0000 48.0609 22.8699 44.2100
29.0000 95.3448 19.0000 37.7300
30.0000 82.7273 30.4394 39.1400
这篇关于MATLAB 查找并将函数应用于重复索引的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!