简体   繁体   中英

Matlab : Minimum of matrix

I need to find the minimum of an entire matrix and it's 'coordinates'. In a matrix like

matrix = 8 7 6 5  
         4 3 2 1

The minimum would be 1 at (2, 4).

This can very simply be done by using find , where you would use the two output version of it. So what you want to do is search for those row and column locations in your matrix that match the minimum value in your matrix.

Therefore:

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

row and col would contain the row and column locations of matrix that are equal to this minimum value. Note that I had to unroll the matrix into a vector by doing matrix(:) . The reason why is because if you were to use min on a matrix, it would by default give you the minimum along each column. Because you want to find the minimum over the entire matrix, you would convert this into a single vector, then find the minimum along the entire vector.

Take note that this will return all row and column locations that match the minimum, so it would actually give row and col as N x 1 column vectors, where N is the total amount of elements in matrix that equal the minimum.

If you only want one match, simply append a 1 as the second parameter to find :

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

Another option, which will work for a tensor of any number of dimensions, is to use min with linear indexing, then use ind2sub to recover the exact indices, if required.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM