select random number from an array with probabilities
29 views (last 30 days)
Show older comments
I have an array of three element: S=[4 3.9 3.8] and I want to randomly select one of those three numbers. The probability of selecting 4 is 0.5, the probability of selecting 3.9 is 0.4 and the probability of selecting 3.8 is 0.1.
Can anyone help me please?
1 Comment
Adam
on 20 Feb 2020
Off the top of my head and unverified because my Matlab is busy and I can't be bothered to start another one:
cumulativeProbs = cumsum( [0.5 0.4 0.1] );
S( find( rand > cumulativeProbs, 1 ) - 1 );
Answers (1)
Sky Sartorius
on 20 Feb 2020
You can query the cumulative probabilities:
S = [4, 3.9, 3.8];
w = [0.5, 0.4, 0.1];
w = w/sum(w); % Make sure probabilites add up to 1.
cp = [0, cumsum(w)];
r = rand;
ind = find(r>cp, 1, 'last');
result = S(ind)
4 Comments
See Also
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!