Get indices of n largest elements in a matrix

Suppose I have the following matrix:

01 02 03 06 03 05 07 02 13 10 11 12 32 01 08 03 

And I need indexes from the 5 best elements (in this case 32, 13, 12, 11, 10). What is the cleanest way to do this in MATLAB?

+50
matrix matlab
Apr 22 '10 at 16:05
source share
3 answers

There are several ways to do this, depending on how you want to deal with duplicate values. Here's a solution that finds indexes for the 5 largest values ​​(which may include duplicate values):

 [sortedValues,sortIndex] = sort(A(:),'descend'); %# Sort the values in %# descending order maxIndex = sortIndex(1:5); %# Get a linear index into A of the 5 largest values 

Here's a solution that finds the 5 largest unique values, then finds all the elements equal to these values:

 sortedValues = unique(A(:)); %# Unique sorted values maxValues = sortedValues(end-4:end); %# Get the 5 largest values maxIndex = ismember(A,maxValues); %# Get a logical index of all values %# equal to the 5 largest values 
+71
Apr 22 '10 at 16:19
source share

If you have a fairly large array and you only need a few elements. That would be my decision.

 Arraycopy = Array; for j = 1:n [a, Index(j)] = max(Arraycopy); Arraycopy(Index(j)) = -inf; end maximumValues = Array(Index); 

I think it should be faster and less RAM than a sorting solution.

+15
Jan 09 2018-12-01T00:
source share

You can find good answers to matlab questions also on matlabcentral. I found a good mex implementation there, looking for the same.

This is done by Bruno Luong using a partial quick sort algorithm implemented using C-MEX. Difficulty is O (n + k.log (k)), where n is the size of the array and k is the number of elements to select. This is faster than SORT or multiple MIN / MAX calls for large input. Multidimensional Support

http://www.mathworks.com/matlabcentral/fileexchange/23576-minmax-selection

+7
Jan 29 '12 at 3:20
source share



All Articles