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

你离开我真会死。 提交于 2019-11-28 20:51:05
Adrien

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!