Given a matrix, it's easy to compute the value and index of the min value:
A = rand(10);
[value, index] = min(A(:));
However I would also like to recover the second min value (idem for max).
I can of course take any of this two approaches:
Converting A to a vector and sorting it.
PROS: I can then recover the second, third... n minimum value
CONS: If A is large, sorting is expensive
Once the min location of A is located, I can replace this value by a large one (eg: Inf) and then run
min
again.PROS: Cheaper than sort
CONS: I must modify my matrix (and save the modified value in an aux variable). Also re-running min is costly on a large matrix.
I'm wondering if there is a better solution:
When computing min
the algorithm has to keep track of the min value found so far, until a new value has a lower value (then we update the value).
If instead we keep track of the last n
min values found so far will allow to recover the minimum n
values.
I can implement this, but I'm wondering if it's the best approach or if it's already implemented.
sort
you can have your 2x lowest min and 2x largest max in one single expensivesort
operation. Otherwise you have to run 2xmin
and 2xmax
. Make a test and find which approach is less expensive. – Evangelicalismsort
is quite fast. Also, you can always (if you have it)gpuarray
it. Reduces are very fast in GPUs – Trap