Grouping rows on the first two columns

7 ビュー (過去 30 日間)
Si Cla
Si Cla 2018 年 2 月 27 日
コメント済み: Si Cla 2018 年 2 月 28 日
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?
  1 件のコメント
KL
KL 2018 年 2 月 27 日
which version are you using?

サインインしてコメントする。

採用された回答

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)
  1 件のコメント
Si Cla
Si Cla 2018 年 2 月 28 日
Thankyou! It works just how I wanted.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeHistorical Contests についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by