Matlab将一行的第一列匹配为索引,然后平均该行中的所有列 [英] Matlab matching first column of a row as index and then averaging all columns in that row
问题描述
在获取以下数据时,我需要帮助,这些数据以大矩阵进行组织,并对具有匹配ID(索引)的所有值求平均值,并输出仅包含ID和跟踪它的平均值的另一个矩阵.
I need help with taking the following data which is organized in a large matrix and averaging all of the values that have a matching ID (index) and outputting another matrix with just the ID and the averaged value that trail it.
File with data format:
(This is the StarData variable)
ID>>>>Values
002141865 3.867144e-03 742.000000 0.001121 16.155089 6.297494 0.001677
002141865 5.429278e-03 1940.000000 0.000477 16.583748 11.945627 0.001622
002141865 4.360715e-03 1897.000000 0.000667 16.863406 13.438383 0.001460
002141865 3.972467e-03 2127.000000 0.000459 16.103060 21.966853 0.001196
002141865 8.542932e-03 2094.000000 0.000421 17.452007 18.067214 0.002490
请不要误解我发布的示例,第一个数字重复大约15行,然后ID更改,然后重复整个不同ID的集合,然后再次将它们作为一个整体重复,请考虑一下第一个块的代码= [1 2 3; 1 5 9; 2 5 7; [2 4 6],然后代码将为索引重复不同的列值(索引除外).主要的区别是,值跟在我需要在matlab中平均的ID后面,并输出一个干净的矩阵,其中每个ID中只有一个ID对于所有出现的ID均被完全平均. 感谢您提供的任何帮助.
Do not be mislead by the examples I posted, that first number is repeated for about 15 lines then the ID changes and that goes for an entire set of different ID's, then they are repeated as a whole group again, think first block of code = [1 2 3; 1 5 9; 2 5 7; 2 4 6] then the code repeats with different values for the columns except for the index. The main difference is the values trailing the ID which I need to average out in matlab and output a clean matrix with only one of each ID fully averaged for all occurrences of that ID. Thanks for any help given.
推荐答案
对此答案所做的修改,如下:
[value_sort ind_sort] = sort(StarData(:,1));
[~, ii, jj] = unique(value_sort);
n = diff([0; ii]);
averages = NaN(length(n),size(StarData,2)); % preallocate
averages(:,1) = StarData(ii,1);
for col = 2:size(StarData,2)
averages(:,col) = accumarray(jj,StarData(ind_sort,col))./n;
end
结果在变量averages
中.它的第一列包含用作索引的值,随后的每一列包含根据索引值对该列的平均值.
The result is in variable averages
. Its first column contains the values used as indices, and each subsequent column contains the average for that column according to the index value.
Matlab 2013a以后的兼容性问题:
函数unique
在Matlab中已已更改 2013a.从该版本开始,将'legacy'
标志添加到unique
,即,将第二行替换为
The function unique
has changed in Matlab 2013a. For that version onwards, add 'legacy'
flag to unique
, i.e. replace second line by
[~, ii, jj] = unique(value_sort,'legacy')
这篇关于Matlab将一行的第一列匹配为索引,然后平均该行中的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!