MATLAB: Finding the indices of all minimum elements in a matrix

getting indices of all min elementsmin

In Matlab, by the function min(), one can get only one single minimum element of a matrix, even if there can be several equal minimum elements. How to get the indices of all minimum elements in a matrix?

Best Answer

You can do it in one line of code. You just first need to decide if you want to locate occurrences of the global min, or if you want to find local mins (using imregionalmin), AND if you want a vector of logical indexes or a vector of actual indexes. Since you didn't say, I'm giving all 4 possibilities:
% Create sample data:
vec = [1,1,2,2,1,2,1,3,0,-1,4,0,3,-1,5];
% Find local mins as a logical index.
localMinIndexes = imregionalmin(vec)
% Find global mins as a logical index.
globalMin = min(vec);
globaMinIndexes = vec == globalMin
% If you want/need actual indexes, use find:
% Find local mins as actual indexes.
localMinIndexes = find(imregionalmin(vec))
% Find global mins as actual indexes.
globaMinIndexes = find(vec == min(vec))