Indices from Max function to Extract Data

2 次查看(过去 30 天)
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]}));

更多回答(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