开发者

How can I find the maximum or minimum of a multi-dimensional matrix in MATLAB? [duplicate]

This question already has answers here: 开发者_开发知识库 Index of max and min value in an array (3 answers) Closed 8 years ago.

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜