How can I find the maximum or minimum of a multi-d

2019-01-22 15:37发布

问题:

This question already has an answer here:

  • Index of max and min value in an array 3 answers

I have a 4D array of measurements in MATLAB. Each dimension represents a different parameter for the measurement. I want to find the maximum and minimum value and the index (i.e. which parameter) of each.

What's the best way to do it? I figure I can take the max of the max of the max in each dimension, but that seems like a kludge.

回答1:

Quick example:

%# random 4 d array with different size in each dim
A = rand([3,3,3,5]);

%# finds the max of A and its position, when A is viewed as a 1D array
[max_val, position] = max(A(:)); 

%#transform the index in the 1D view to 4 indices, given the size of A
[i,j,k,l] = ind2sub(size(A),position);

Finding the minimum is left as an exercise :).

Following a comment: If you do not know the number of dimensions of your array A and cannot therefore write the "[i,j,k,l] =" part, use this trick:

indices = cell(1,length(size(A)));

[indices{:}] = ind2sub(size(A),position);


回答2:

for two dimensional array, say I you can just use the min /max function twice. n times for n dimensional array. eg: a=[2 3 4; 5 6 7; -2 7 87; 911 7 34];

for minimum:  min(min(a,[],1))
             ->  the answer will be -2. 

you can put the dimension parameter in min/max to 2 as well. as this is calling the function twice, second time on the minimum/maximum element vector of the dimension u choose.

similarly, you can do (max(max(a,[],1)) to find out the maximum.