Finding maximum y value corresponding to same x values.

조회 수: 8 (최근 30일)
Erin
Erin 2013년 2월 21일
I have a n by 2 array.
x y
1 5
1 7
1 9
2 8
2 22
2 11
5 5
5 10
5 20
I'd like to spit out an array of the max y coordinate that corresponds to each x coordinate. So I'd have:
1 9
2 22
5 20
Thanks for any help!

답변 (3개)

Sean de Wolski
Sean de Wolski 2013년 2월 21일
xy = [
1 5
1 7
1 9
2 8
2 22
2 11
5 5
5 10
5 20];
[uv,~,idx] = unique(xy(:,1)); %what do they correspond to?
xmax = accumarray(idx,xy(:,2),[],@max); %build matrix
[uv xmax]

Azzi Abdelmalek
Azzi Abdelmalek 2013년 2월 21일
편집: Azzi Abdelmalek 2013년 2월 22일
[a,b]=unique(x);
for jj=1:numel(a);
e(jj)=max(y(x==a(jj)));
end
result=[a e]

Shashank Prasanna
Shashank Prasanna 2013년 2월 21일
Quickest way I can think of is using accumarray:
% let xy be your array
A = accumarray(xy(:,1), xy(:,2), [], @max)
[unique(xy(:,1)) A(A~=0)]
ans =
1 9
2 22
5 20
  댓글 수: 2
Sean de Wolski
Sean de Wolski 2013년 2월 22일
편집: Sean de Wolski 2013년 2월 22일
If you run the unique command first, you skip having to remove the zeros. With 1,2,5 whatever, with 1,2, 5000000 you run out of memory...
With my approach, you build a 1x3 vector regardless of the values, even if they're non-integer :)
Shashank Prasanna
Shashank Prasanna 2013년 2월 22일
That's good to note! I didn't see your reply before i put mine in. Thanks for the tip!

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by