MATLAB: Finding the position of the 1st,2nd and 3rd max value in a matrix

matrix arrayprogramming

Hi, I want to find the position of the 1st,2nd and 3rd maximum value of a matrix.I know that I can find the position of the max value using find() function like:(e.g. X is a matrix)
[i j]=find(X==max(X))
but it gives just the position of max value.
Thanks,
Amin.

Best Answer

If X is not unique, find(X==max(X)) can find more than one element. Then Sven's sort method yields to another reply.
For large arrays sorting is expensive. You can try this:
[max1, ind1] = max(X);
X(ind1) = -Inf;
[max2, ind2] = max(X);
X(ind2) = -Inf;
[max3, ind3] = max(X);
X(ind3) = -Inf;
For X = rand(1, 1e6) this is 4.7 times faster than the SORT-method under Matlab 2009a, Win7/64.