Matlab: minimal matrix

I need to find the minimum of the entire matrix and its "coordinates". In a matrix like

matrix = 8 7 6 5  
         4 3 2 1

      

The minimum will be 1 in (2, 4).

+3


source to share


2 answers


This can be done simply with find

, where you would use two output versions. So, you want to find those rows and columns in your matrix that match the minimum value in your matrix.

Thus:

[row, col] = find(matrix == min(matrix(:)));

      

row

and col

will contain the arrangement of rows and columns matrix

that are equal to this minimum value. Note that I had to unwrap the matrix into a vector by doing matrix(:)

. The reason is that if you have to use min

on a matrix, it will by default give you the minimum for each column. Since you want to find the minimum over the entire matrix, you must convert that to one vector and then find the minimum over the entire vector.



Note that this will return the columns of rows and columns of all , which will correspond to a minimum, so it actually provides row

, and col

as a column vector N x 1

, where N

the total number of elements in the matrix

equal to a minimum.

If only one is required , just add 1 as the second parameter to find

:

[row, col] = find(matrix == min(matrix(:)), 1);

      

+3


source


Another option that will work for a tensor of any number of dimensions is to use min

with linear indexing, then use ind2sub

to recover exact indexes if needed.



[~, nIndex] = min(matrix(:));
[nIndex1, nIndex2, nIndex3, ...] = ind2sub(size(matrix), nIndex);

      

0


source







All Articles