Finding the smallest element index in a three-dimensional matrix (or n-dimensional)

I have a matrix D(i,j,k) , and I want to find i , j , k to minimize x :

 x = D(i,j,k) 

For instance:

 D = rand(10,10,10); min(min(min(D))) = 0.5123; %The smallest element in D 

What I want to know is the D index, which gives 0.5123

How can i do this? Thanks, Elliot

+6
source share
3 answers

Try min with the colon statement, then ind2sub :

 [xmin,ind] = min(D(:)); [ii,jj,kk] = ind2sub(size(D),ind) 
+7
source

Answer by @chappjc is perfect for the 3D case.

For the case of n-dimensional, use ind2sub a as a comma-separated list obtained from an array of cells of size n:

 indices = cell(1,ndims(D)); %// define number of indices (size of cell array) [minVal linInd] = min(D(:)); %// linear index of minimizer [indices{:}] = ind2sub(size(D),linInd); %// return indices in cell array indices = cell2mat(indices); %// convert to nx1 vector containing the indices 
+5
source

You can use the find function.

 D = rand(10,10,10); [I, J]=find(D == min(min(min(D)))); 

Please note that for matrices with more than two dimensions:

If X is an N-dimensional array, where N> 2, then J is a linear index over N-1 terminating the dimensions of X

see http://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html

Hope this helps

+1
source

All Articles