GROUP BY in MATLAB

♀尐吖头ヾ 提交于 2019-12-23 08:10:16

问题


I want to do what SQL's GROUP BY does in MATLAB. For example,

M = [
1, 5;
2, 5;
3, 5;
1, 6;
2, 6;
1,7 ]

SQL: SELECT MAX(c1), c2 FROM M(c1, c2) GROUP BY 2

Result = [
3, 5;
2, 6;
1, 7]

How can I do this in Matlab?


回答1:


grpstats in the Statistics Toolbox can do this:

>> [grpstats(M(:,1), M(:,2), {'max'}) unique(M(:,2))]

ans =

     3     5
     2     6
     1     7



回答2:


If you don't mind doing some preprocessing to get the order (or if the first column is nicely built from 1 to n), you can do it like this:

accumarray([1 2 3 1]',[11 12 13 14]',[],@max)

This will give:

14
12
13

Or in your case:

accumarray(M(:,1),M(:,2),[],@max)

Note the order. The second number for example, will correspond to M(:,1) == 2




回答3:


I think there is a simple solution to this. Here is what I tested on Matlab and it worked:

>> M = [
1, 5;
2, 5; 
3, 5;
1, 6;
2, 6;
1,7 ];

>> grpstats(M,M(:,2),{'max'})

ans =

     3     5
     2     6
     1     7


来源:https://stackoverflow.com/questions/8946845/group-by-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!