Finding the indices of all minimum elements in a matrix
57 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Image Analyst
on 29 Dec 2016
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))
7 Comments
Image Analyst
on 14 Sep 2021
@james sinos that was an example for 2-D matrices. Both P and N are 2-D. Of course extractedN is 1-D. Not sure what you're looking for.
Here's another 2-D example where I also add the creation of a masked 2-D array where the location of the mins in m2 are also the same value in the same locations for m3.
% Demo by Image Analyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format short g;
format compact;
fontSize = 20;
% Create some arbitrary matrix.
m1 = 1000 * rand(8, 8)
% Create sample data with the min at multiple locations:
m2 = randi(9, 8, 8)
% Determine the min value:
minValue = min(m2(:))
% Find rows and columns where the min occurs:
[r, c] = find(m2 == minValue)
% Extract those locations of m1 into a new matrix
for k = 1 : length(r)
extractedN(k) = m1(r(k), c(k));
end
% Show 1-D extracted numbers in command window:
extractedN
% Make a 2-D matrix where everything is -99999 (or whatever you want)
% except for where there's a min in m2.
m3 = -99999 * ones(8,8);
m3(m2 == minValue) = minValue
More Answers (0)
See Also
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!