Bazman
Bazman

Reputation: 2150

Row and Column Indices fo the n largest elements in a matrix

I have a very similar problem to the one solved here:

Get the indices of the n largest elements in a matrix

However this solution converts the matrix to an array and then gives the indices in terms on the new array.

I want the row and column indices of the original matrix for the maximum (and minimum) n values.

Upvotes: 0

Views: 1951

Answers (1)

Alan
Alan

Reputation: 3417

If you take the solution in that question for finding the 5 largest unique 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

You are provided with a logical matrix of those values which match. You can use find to get their indexes and then ind2sub to convert these back to coordinates.

idx = find(maxIndex);
[x y] = ind2sub(size(A), idx);

An alternative, in light of comments:

[foo idx] = sort(A(:), 'descend'); %convert the matrix to a vector and sort it
[x y] = ind2sub(size(A), idx(1:5)); %take the top five values and find the coords

Note: the above method does not eliminate any duplicate values, so for example if you have two elements with the same value it may return both elements, or if they are on the boundary, only one of the two.

Upvotes: 3

Related Questions