Suppose I have the following matrix:
01 02 03 06
03 05 07 02
13 10 11 12
32 01 08 03
And I want the indices of the top 5 elements (in this case, 32, 13, 12, 11, 10). What is the cleanest way to do this in MATLAB?
Suppose I have the following matrix:
01 02 03 06
03 05 07 02
13 10 11 12
32 01 08 03
And I want the indices of the top 5 elements (in this case, 32, 13, 12, 11, 10). What is the cleanest way to do this in MATLAB?
You can find good answers to matlab questions also on matlabcentral. I found a good mex implementation there while searching for the same thing.
It is done by Bruno Luong using a partial quick-sort algorithm implemented with C-MEX. The complexity is O(n + k.log(k)), where n is the size of the array, and k is the number of elements to be selected. It is faster than SORT or multiple call of MIN/MAX for large size inputs. Multidimensional capability supported
http://www.mathworks.com/matlabcentral/fileexchange/23576-minmax-selection
If you have a rather big array and only want a few elements out of it. This would be my solution.
I think it should be faster and less RAM demanding than the sort solution.
In MATLAB ≥ R2017b, you can use
maxk
for this specific purpose.There are a couple ways you can do this depending on how you want to deal with repeated values. Here's a solution that finds indices for the 5 largest values (which could include repeated values) using
sort
:Here's a solution that finds the 5 largest unique values, then finds all elements equal to those values (which could be more than 5 if there are repeated values), using
unique
andismember
: