Value of B at the maximum of A
1 view (last 30 days)
Show older comments
Sylvain Catherine
on 1 Dec 2015
Answered: Sylvain Catherine
on 1 Dec 2015
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
Accepted Answer
More Answers (1)
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
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
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.
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!