0

How can I find the (i, j) index of the minimum element of a matrix?

For example:

M = [3 6 2; 5 5 9; 1 4 4];

I would want to get the output (3, 1).

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247

3 Answers3

6

Try this:

M = [3 6 2; 5 5 9; 1 4 4];
[~, ind] = min(M(:));
[i, j] = ind2sub(size(M), ind);
nicolas
  • 3,120
  • 2
  • 15
  • 17
1
[r,c]=find(M==min(M(:)))

Hope this helps...

lakshmen
  • 28,346
  • 66
  • 178
  • 276
  • Could possibly run into issues comparing floats here. – sco1 Jul 30 '14 at 13:43
  • 1
    @excaza I don't see why that would be a problem, `min` doesn't perform any calculations so it should return an exact match – Dan Jul 30 '14 at 13:57
  • @excaza - There should be no floating point compare issues. First you are retrieving the minimum floating point value from this array, then you're comparing **this exact** value that was extracted from this array to all of the other points in this array. This would only be an issue if you extracted a minimum, then performed some calculations on the matrix, and then tried to do a compare..... and I just basically regurgitated what Dan said, but I just wanted to put my two cents in. – rayryeng Aug 11 '14 at 22:40
-1
[value,index] = min(M(:))

will give:

value = 1
index = 3
Benoit_11
  • 13,905
  • 2
  • 24
  • 35
  • 1
    This is not what was asked, you could call `sub2ind` on your `index` value to get the correct answer though but this is a linear index when the OP asks for a subscript index – Dan Jul 30 '14 at 13:19
  • Oh damn you're right sorry about that I misread the question. – Benoit_11 Jul 30 '14 at 13:21