convenient way to achieve max value in matrix and it location

2 views (last 30 days)
Hi:
I have a 3-dimension matrix, a*b*c, I want to achieve the max value at 3rd dimension, and their corresponding location.
I use command: [a,b] = max(test,[],3);
however, the teturned matrix is with size a*b, but I expect it to be c*1 (maximum value), and maybe a list of 2-dimension matrix that indicate the location of maximum value.
not sure if there is any mistake with my command or understanding, thanks for the help here.
Thanks!
Yu

Accepted Answer

the cyclist
the cyclist on 9 Oct 2023
Edited: the cyclist on 9 Oct 2023
% Define a smaller array, so we can see what is going on
test = cat(3,[2 3; 5 7; 9 11],[1 4; 6 0; 8 12])
test =
test(:,:,1) = 2 3 5 7 9 11 test(:,:,2) = 1 4 6 0 8 12
You can see that we have two "pages", each of which is 2x3. To find the maximum along the 3rd dimension, we are going to be finding the max of each of the following pairs of value:
  • (2,1)
  • (5,6)
  • (9,8)
  • (3,4)
  • (7,0)
  • (11,12)
[maxValue,indexAlongTargetDimension] = max(test,[],3); % Do the max along the 3rd dimension, but with intuitive output names
maxValue
maxValue = 3×2
2 4 6 7 9 12
indexAlongTargetDimension
indexAlongTargetDimension = 3×2
1 2 2 1 1 2
The maximumValue array has 3x2 values, because there are 3x2 vectors pointing along the 3rd dimension, and you are getting the maximum value along each of those vectors. (These are the six comparisons I listed above, but of course arranged 3x2, like the original array.)
Then indexAlongTargetDimension tells you how far along each of those vectors you go, to find the max. Namely,
  • (2,1) -- 1st value is max
  • (5,6) -- 2nd value is max
  • (9,8) -- 1st value is max
  • (3,4) -- 2nd value is max
  • (7,0) -- 1st value is max
  • (11,12) -- 2nd value is max
I hope that helps.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!