Grouping rows on the first two columns

7 次查看(过去 30 天)
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?

采纳的回答

Jos (10584)
Jos (10584) 2018-2-27
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)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Historical Contests 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by