convenient way to achieve max value in matrix and it location

조회 수: 2 (최근 30일)
Yu Li
Yu Li 2023년 10월 9일
댓글: Yu Li 2023년 10월 9일
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

채택된 답변

the cyclist
the cyclist 2023년 10월 9일
편집: the cyclist 2023년 10월 9일
% 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.

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by