GROUP BY in MATLAB

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

M = [
fifteen;
2, 5;
3, 5;
sixteen,
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?

+7
source share
3 answers

grpstats in the statistics toolbar can do this:

 >> [grpstats(M(:,1), M(:,2), {'max'}) unique(M(:,2))] ans = 3 5 2 6 1 7 
+4
source

If you don't mind doing some preprocessing to get the order (or if the first column is well 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) 

Pay attention to the order. For example, the second number will correspond to M(:,1) == 2

+3
source

I think there is a simple solution. 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 
+2
source

All Articles