Grouping rows on the first two columns

6 vues (au cours des 30 derniers jours)
Si Cla
Si Cla le 27 Fév 2018
Commenté : Si Cla le 28 Fév 2018
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?

Réponse acceptée

Jos (10584)
Jos (10584) le 27 Fév 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)
  1 commentaire
Si Cla
Si Cla le 28 Fév 2018
Thankyou! It works just how I wanted.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Historical Contests dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by