How to randomly pick up N numbers from a vector a with weight assigned to each number?
Let’s say:
a = 1:3; % possible numbers
weight = [0.3 0.1 0.2]; % corresponding weights
In this case probability to pick up 1 should be 3 times higher than to pick up 2.
Sum of all weights can be anything.
randsample is included in the Statistics Toolbox
Otherwise you can use some kind of roulette-wheel selection process. See this similar question (although not MATLAB specific). Here’s my one-line implementation:
Explanation:
Consider the interval [0,1]. We assign for each element in the list (
1:3) a sub-interval of length proportionate to the weight of each element; therefore1get and interval of length0.3/(0.3+0.1+0.2), same for the others.Now if we generate a random number with uniform distribution over [0,1], then any number in [0,1] has an equal probability of being picked, thus the sub-intervals’ lengths determine the probability of the random number falling in each interval.
This matches what I’m doing above: pick a number X~U[0,1] (more like
Nnumbers), then find which interval it falls into in a vectorized way..You can check the results of the two techniques above by generating a large enough sequence
N=1000:which more or less match the normalized weights
w./sum(w)[0.5 0.16667 0.33333]