MATLAB: Find the location of the n largest (non-unique) values in a matrix

findlocationmatrixmaxnon-unique

I'm trying to write some code that generates a n x 2 matrix that describes the location of the n largest values in a large matrix called "BinConcentrationCopy" (which is a 12 x 24 matrix). Here's the code I've been working with so far:
for n = 1:5
[row(n), column(n)] = find(BinConcentrationCopy==max(max(BinConcentrationCopy)));
BinConcentrationCopy(row(n), column(n)) = 0;
end
location = [row; column];
This code works perfectly and generates the correct 5×2 "location" matrix if the 5 largest values in my BinConcentrationCopy are all unique numbers; however, this isn't always the case. If, for example, the 3rd largest value in BinConcentrationCopy shows up twice (aka it's the 3rd and the 4th largest value for that matrix) then an error occurs and the for loop quits before iterating all the way through. Any ideas on how to debug this? Thanks in advance.

Best Answer

Here is a quite different approach:
% Some pretend data with a duplicated max value
BinConcentrationCopy = magic(7);
BinConcentrationCopy(1,1) = 49;
% The algorithm
n = 5;
[~,sortingIndex] = sort(BinConcentrationCopy(:),'desc')
[row, col] = ind2sub(size(BinConcentrationCopy),sortingIndex(1:n))