Grouping rows on the first two columns
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Si Cla
am 27 Feb. 2018
Kommentiert: Si Cla
am 28 Feb. 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?
Akzeptierte Antwort
Jos (10584)
am 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)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Historical Contests finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!