0

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.

Community
  • 1
  • 1
Bazman
  • 2,058
  • 9
  • 45
  • 65

1 Answers1

3

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.

Alan
  • 3,307
  • 1
  • 19
  • 22
  • worked with [row col] = ind2sub(size(A), idx); note though that although the row and columns given do relate to the largest five elements, they are not given in order which is a little confusing? Can this be fixed? eg idx=159 910 1005 2188 2913 row=3 4 3 4 3 col=27 152 168 365 486 the maximum is in column 486 so that#s correct but the 2nd max is in 168? – Bazman Apr 16 '13 at 17:11
  • so although 168 is listed in col[] it's in the third position even though it represents the 2nd largest element of the original matrix? – Bazman Apr 16 '13 at 17:17
  • Thanks for picking up the output error, I have fixed that in the answer. Also, indeed the result was unordered. The method from the other question returned a logical index, which has no ordering. I didn't really give that part much attention, as I focused on the converting the indexes back to referring to the matrix. I have added an alternative method to my answer, but it's all the same sort of thing: get the indexes of the elements you want, in the order you want then throw them through `ind2sub`. – Alan Apr 16 '13 at 17:29