Grouping rows on the first two columns

6 views (last 30 days)
Hello,
I have a nx3 matrix for which I need to a) group cells which have matching values in the first and second columns, b) find the max value in the third column for each of these groups, b) remove the rows that contain the max values
e.g.
Matrix:
13 30 7
13 30 6
13 40 5
13 40 6
12 30 7
12 37 5
Group values on first two columns:
13 40 5
13 40 6
Find max value and remove row from matrix:
13 30 7
13 30 6
13 40 5
12 30 7
12 37 5
This needs to be done for every group. I tried a for loop to iterate through each group, but I'm having trouble grouping rows on the first two columns. My code is currently:
for i =1:nr
% group on first two columns
L = A(:,1)==A(i,1)& A(:,2)==A(i,2);
A2=A(L,:);
%find max value for each
A(i,3)=max(A2(:,3));
end
Does anyone know a better approach?

Accepted Answer

Jos (10584)
Jos (10584) on 27 Feb 2018
A = [13 30 7
13 30 6
13 40 5
13 40 6
12 30 7
12 37 5] ;
% engine
[B,~,gi] = unique(A(:,[1 2]),'rows','stable') % unique rows, with grouping index
B(:,3) = accumarray(gi(:), A(:,3), [], @max)

More Answers (0)

Categories

Find more on Historical Contests in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!