I want to find the n largest values in a matrix and replace all others with zero.
The solution I found uses ReplaceAll
and becomes very slow as the size of matrices grows:
FindLargestValues[m_?MatrixQ, n_Integer] :=
With[{v = (Union @ Flatten @ m)[[-n]]},
m /. x_Real /; x < v :> 0]
Example:
(small = RandomReal[{1, 10}, {5, 5}]) // MatrixForm
FindLargestValues[small, 10] // MatrixForm
Timing example:
large = RandomReal[{1, 10}, {50, 50}];
Do[FindLargestValues[large, 50], {1000}]; // Timing // First
2.574016
Is there a faster way to do this?