MATLAB Answers

How to pick a value according to its probability

446 views (last 30 days)
Steven on 7 Dec 2011
Commented: krishna teja on 20 Apr 2020
Let's say
P = [0.1 0.3 0.4 0.2]
X = [1 2 5 9]
where P(n) is the probability to select the X(n) element. I wish to make a function that select a "random" element of X according to its probability, like
f = myfun(P,X)
>> f = 2 (occurs around 30%)
thx a lot
how to select an element with least probablility

Sign in to comment.

Accepted Answer

Sean de Wolski
Sean de Wolski on 7 Dec 2011
f = X(find(rand<cumsum(P),1,'first'))
  1 Comment
Walter Roberson
Walter Roberson on 7 Dec 2011
The answers in the other thread took care in case cumsum(P) < 1 as can happen due to round-off error.

Sign in to comment.

More Answers (2)

Jonathan on 3 Sep 2018
Edited: Jonathan on 3 Sep 2018
The accepted answer is not doing any sanity check, and is sensitive to rounding errors. You should use randsample instead.
To sample n points from X, with replacement, and probabilities P:
randsample( X, n, true, P )
This can also be used with a custom RandStream (see documentation). Be aware that this function does NOT check for negative values in P; check manually if needed.

Steven Lord
Steven Lord on 16 Apr 2020
You can use discretize (which didn't exist when this question was asked originally) to do this. Generate uniform random numbers, bin them using bins whose widths are given by P, and for each bin return the corresponding element of X.
P = [0.1 0.3 0.4 0.2];
X = [1 2 5 9];
values = discretize(rand(1, 1e4), cumsum([0 P]), X);
histogram(values, 'Normalization', 'probability')
The probabilities shown in the histogram should agree pretty closely with the values in P.

Community Treasure Hunt

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

Start Hunting!

Translated by