Search code examples
matlabmaxminimum

Find extremum of multidimensional matrix in matlab


I am trying to find the Extremum of a 3-dim matrix along the 2nd dimension.

I started with [~,index] = max(abs(mat),[],2), but I don't know how to advance from here. How is the index vector to be used together with the original matrix. Or is there a completely different solution to this problem?

To illustrate the task assume the following matrix:

mat(:,:,1) =
    23     8    -4
    -1   -26    46
mat(:,:,2) =
     5   -27    12
     2    -1    18
mat(:,:,3) =
   -10    49    39
   -13   -46    41
mat(:,:,4) =
    30   -24    18
   -40   -16   -36

The expected result would then be

ext(:,:,1) =
    23
   -46
ext(:,:,2) =
   -27
    18
ext(:,:,3) =
    49
   -46
ext(:,:,4) =
    30
   -40

I don't know how to use the index vector with mat to get the desired result ext.


Solution

  • Use ndgrid to generate the values along dimensions 1 and 3, and then sub2ind to combine the three indices into a linear index:

    [~, jj] = max(abs(mat),[],2); %// jj: returned by max
    [ii, ~, kk] = ndgrid(1:size(mat,1),1,1:size(mat,3)); %// ii, kk: all combinations
    result = mat(sub2ind(size(mat), ii, jj, kk));
    

    A fancier, one-line alternative:

    result = max(complex(mat),[],2);
    

    This works because, acccording to max documentation,

    For complex input A, max returns the complex number with the largest complex modulus (magnitude), computed with max(abs(A)).