Bruno, I see that you have also written a very nice implementation for this purpose (mink and maxk). Again using your example with a million points, I find that if N is 1000, findNlargest runs about 2.5 times faster than maxk, but for larger N maxk is faster. If the poolsize is 5 million and N is 1000, findNlargest is over 7 times faster than maxk. So, users should be aware that this function is specialized for choosing a small number of values from a large pool. Otherwise maxk and mink will perform better in the general case.

Hi Bruno,
As far as retrieving the index goes, it seems to work fine when I do it:

a = rand(1,1e6);
[x,index] = findNlargest(a,5)

x =

1.0000
1.0000
1.0000
1.0000
1.0000

index =

878652
294446
965700
961872
165538

In this case, if there are more than 5 of the same max value, then the first 5 would be chosen.

And for the second point, yes, this code is intended for cases when you are choosing a small number of values from a large pool. In your example (with a pool of a million values), if N = 5, my code is about 40 times faster than sorting. If N = 1000, my code is 6 times faster. Once N is greater than half the sample size, it makes more sense to find the poolsize-N smallest values. (see findNsmallest).