MATLAB Answers

# select random number from an array with probabilities

104 views (last 30 days)
Margherita Premoli on 20 Feb 2020
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 CommentShowHide None
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 );

Sign in to comment.

### 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 CommentsShowHide 3 older comments
Margherita Premoli on 21 Feb 2020
okay great, now it is clar! thanks again :)

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!