Knowing that most weights are equal to zero you can rewrite a faster implementation of randsample
from Octave source. In my timing it is 6X-7X
faster than the original implementation:
function y = randsample_fast(v, w)
f = find(w);
w = w(f);
w = w / sum(w);
w = [0 cumsum(w)];
y = f(lookup (w , rand));
%y = f(find (w <= rand, 1, "last"));
y = v(y);
end
- Inputs are assumed to be row vectors.
- Changing
find
to lookup
may slightly improve the performance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…