Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the indices of the n largest elements in a matrix

Tags:

matrix

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?

like image 894
Vlad the Impala Avatar asked Apr 22 '10 16:04

Vlad the Impala


People also ask

How do you find the indices of a matrix?

Description. k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.

How do you find the indices of N maximum values in a NumPy array?

In order to get the indices of N maximum values in a NumPy array, we can use the argsort() function.

How do you find the N largest value in an array?

For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy. argsort() function of NumPy then applying slicing concept with negative indexing. Return: [index_array, ndarray] Array of indices that sort arr along the specified axis.

How do I find the largest n value in an array in Matlab?

Description. B = maxk( A , k ) returns the k largest elements of A . If A is a vector, then maxk returns a vector containing the k largest elements of A .


2 Answers

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:

[~, 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 elements equal to those values (which could be more than 5 if there are repeated values), using unique and ismember:

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 
like image 57
gnovice Avatar answered Sep 29 '22 11:09

gnovice


If you have a rather big array and only want a few elements out of it. This would be my solution.

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 demanding than the sort solution.

like image 31
Sebastian Avatar answered Sep 29 '22 09:09

Sebastian