Value of B at the maximum of A

1 view (last 30 days)
My problem is quite simple. I have two arrays A and B of identical size and having N dimensions.
I want to compute the max of A along its Nth dimension and to get the corresponding values in array B.
I see several complicated ways to to it, but I guess that there must be an elegant and efficient one I am missing.
Thanks a lot for your help,
-------
Edit (cf. comments) :
A non-vectorized version of I want is:
A = randi(99, 4, 5, 3) ;
B = randi(99, 4, 5, 3) ;
[Amax,Idx] = max(A,[],3) ;
for i=1:4 ;
for j=1:5 ;
C(i,j) = B(i,j,Idx(i,j)) ;
end
end
  1 Comment
Star Strider
Star Strider on 1 Dec 2015
Three hours ago that would have been helpful.

Sign in to comment.

Accepted Answer

Sylvain Catherine
Sylvain Catherine on 1 Dec 2015
Here is a way to do it. I am not sure it's the best way however...
size1 = 4 ;
size2 = 5 ;
size3 = 3 ;
A = randi(99, size1, size2, size3) ;
B = randi(99, size1, size2, size3) ;
[Amax,Idx] = max(A,[],3) ;
IDX = 1:size1*size2 ;
IDX = reshape(IDX,size1,5) + (Idx-1)*size1*size2;
C = B(IDX) ;

More Answers (1)

Star Strider
Star Strider on 1 Dec 2015
Unless I don’t understand what you want, you can use the max function with two outputs.
For example, to get the maximum along the third dimension of a 3-dimensional matrix, and then get the corresponding elements from another matrix of the same size this works:
A = randi(99, 4, 5, 3)
B = randi(99, 4, 5, 3)
[Amax,Idx] = max(A,[],3)
C = B(:,:,Idx) % Desired Result
  5 Comments
Star Strider
Star Strider on 1 Dec 2015
The Amax and Idx matrices are themselves both 4x5 (in my example code), so they meet your expectations.
In creating ‘C’, it then ‘pages’ through the dimensions of ‘B’ and creates the 20 dimension ‘C’ matrix by creating a single (4x5) matrix from each index in ‘Idx’. Walter’s analysis is correct, as is the result MATLAB produces by default.
If the result of your ‘non-vectorised’ loop is the result you want, then go with it. You did not specify the result you wanted in your original Question.
Walter Roberson
Walter Roberson on 1 Dec 2015
I know a vectorized version is possible; at the moment it is not clear to me that it can be done efficiently.

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!