finding unique rows with largest value in 3rd column

Suppose I have a matrix
A=
1 2 3
1 3 8
2 1 3
2 1 5
2 2 8
1 2 9
4 3 2
I want to find a matrix which has unique first column and largest 3rd column.. So my resultant matrix should be
1 2 9
2 2 8
4 3 2
Any help will be highly appreciated!

댓글 수: 2

So the order of the first two columns doesn't matter?
No order doesn't matter. Actually second column is not useful. Uniqueness is based on first column and one having largest value of 3rd column is selected.

댓글을 달려면 로그인하십시오.

 채택된 답변

Sean de Wolski
Sean de Wolski 2013년 12월 19일
편집: Sean de Wolski 2013년 12월 19일
Assuming that the order of the first two columns doesn't matter and that your expected matrix is missing [1 3 8]
Old/clarified in comments
x = [1 2 3
1 3 8
2 1 3
2 1 5
2 2 8
1 2 9
4 3 2];
[uv,~,idx] = unique(sort(x(:,[1 2]),2),'rows');
v = accumarray(idx,x(:,3),[],@max);
vv = [uv v]
vv =
1 2 9
1 3 8
2 2 8
3 4 2

댓글 수: 5

He only wanted one row with 1 in the first column not two, and that would be the row that had 9 in column 3, not 8 because 9 is larger than 8.
Yes you are right... I want only one row with 1 in first column
Even less work:
x = [1 2 3
1 3 8
2 1 3
2 1 5
2 2 8
1 2 9
4 3 2];
[uv,~,idx] = unique(x(:,1));
v = accumarray(idx,x(:,3),[],@max);
vv = [uv v]
vv =
1 9
2 8
4 2
Thanks! I want to preserve the second column information, I need that in future... so I want all the 3 columns in my answer... I am sure it must be a small modification but I am unable to do it
Well do you want the first occurrence of the second column or the maximum one? etc. I guess, how do you wish to pick the second value (e.g. 2 1 v. 2 2)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Muhammet Bozkaya
Muhammet Bozkaya 2017년 11월 20일
편집: Muhammet Bozkaya 2017년 11월 20일
Simple answer for this case.
First sort rows with ascending 1st column and descending 3rd column(column you want to get the max), then see take unique...
A=[1 2 3
1 3 8
2 1 3
2 1 5
2 2 8
1 2 9
4 3 2];
A=sortrows(A,[1 -3]);
[~,idx]=unique(A(:,1));
A=A(idx,:);
result: 1 2 9
2 2 8
4 3 2

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2013년 12월 19일

편집:

2017년 11월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by