finding unique rows with largest value in 3rd column
5 views (last 30 days)
Show older comments
Mahi Nazir
on 19 Dec 2013
Edited: Muhammet Bozkaya
on 20 Nov 2017
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 Comments
Accepted Answer
Sean de Wolski
on 19 Dec 2013
Edited: Sean de Wolski
on 19 Dec 2013
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 Comments
Sean de Wolski
on 19 Dec 2013
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)
More Answers (1)
Muhammet Bozkaya
on 20 Nov 2017
Edited: Muhammet Bozkaya
on 20 Nov 2017
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
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!