Indices from Max function to Extract Data

조회 수: 2 (최근 30일)
Rajesh Rajaram
Rajesh Rajaram 2015년 3월 11일
댓글: Rajesh Rajaram 2015년 3월 11일
I have two arrays:
A=[1 2; 3 2; 3 4];
B=[1 2; 3 4; 5 6];
When I calculate [M,I] = max(A,[],2), I get
M =
2
3
4
I =
2
1
2
Which is fine. Now I want to report values of B for the When A=M in each row; that is:
1
4
5
Is there a way to avoid using the for loop to build my answer array (have a large data set)? I used:
[I_row, I_col] = ind2sub(size(A),I)
but that doesn't seem to help my cause. Kindly help
Thanks in advance
  댓글 수: 2
Andrew Newell
Andrew Newell 2015년 3월 11일
Your question gets a little garbled in the middle, and I'm not sure what you're after. If you want the values [1 4 5] from B, those correspond to the position of the minima in each row of A. Is that what you want?
Rajesh Rajaram
Rajesh Rajaram 2015년 3월 11일
So sorry for the confusion. My bad!! I just need the values of B corresponding to the position which has the max values of A.
2 3 6 (and not what I typed. SORRY!!)
I have since found the expression B(sub2ind(size(A), 1:size(A,1), I'))' which seems to do the trick.
But if I want the dim in max function to be changed from 2 to 1, then I have to manually input for sub2ind to get my desired answer.
Is there a generic expression to get the right answer irrespective of the dim that I use in the max function?

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2015년 3월 11일
편집: Andrei Bobrov 2015년 3월 11일
A=[1 2; 3 2; 3 4];
B=[1 2; 3 4; 5 6];
n = 1;
[~,I]=max(A,[],n);
c ={(1:size(A,3-n))',I(:)}; % EDIT
l = n == 1;
out = B(sub2ind(size(A),c{[l,~l]+[1,1]}));
  댓글 수: 3
Andrei Bobrov
Andrei Bobrov 2015년 3월 11일
fixed
Rajesh Rajaram
Rajesh Rajaram 2015년 3월 11일
Thank you so much!!

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

추가 답변 (0개)

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by