Question

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.

Était-ce utile?

La solution 2

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)).

Autres conseils

1) If you want to find a maximum just along, let's say, 2d dimension, your variable index will be a matrix having dimensions (N,1,M), where N and M are number of elements of your matrix in the first and third dimensions respectively. In order to remove dummy dimensions, there is function squeeze() exist: index=squeeze(index) After that size(index) gives N,M

2) Depending on your problem, you probably need matlab function ind2sub(). First, you take a slice of your matrix, than find its maximum with linear indexing, and than you can restore your indicies with int2sub(). Here is an example for a 2D matrix:

M = randn(5,5);
[C,I] = max(M(:));
[index1,index2] = ind2sub(size(M),I);

Same method allows to find the absolute maximal element in whole 3D matrix.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top