choose max among elements with same column 1 value, different column 2 value

consider a nx2 matrix like:
A = [1 0.7
2 0.5
2 0.6
2 0.3
3 0.4
3 0.1
4 0.7
5 0.3
5 0.3]
I want to create mx2 matrix B subset of A where B as the properties:
  1. B(:1) = unique(A(:,1))
  2. If a value in column 1 of A appears more than once, then B will contain the row from A which has greatest value in column 2 of A
so the answer to the given example would be
B = [1 0.7
2 0.6
3 0.4
4 0.7
5 0.3]
I can easily do this with for-loops and stuff, but I was wondering if anyone could come up with an elegant MATLAB one-liner , or perhaps two- or three-liner? :)
(It makes my MATLAB skills better to see how the pros do it in one- two- or three-liners)
Thank you!

 채택된 답변

Matt J
Matt J 2014년 3월 4일
편집: Matt J 2014년 3월 4일
B(:,2)=accumarray(A(:,1), A(:,2),[],@max );
B(:,1)=(1:size(B,1)).'

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

질문:

2014년 3월 4일

편집:

2014년 3월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by