# How to pick a value according to its probability

242 views (last 30 days)
Steven on 7 Dec 2011
Commented: Sepehr Saadatmand on 11 Oct 2019
Hi,
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

Oleg Komarov on 7 Dec 2011
This is a double post. See my comment on Andrei's answer: http://www.mathworks.com/matlabcentral/answers/23319-easy-question-with-probability
Nikolas Spiliopoulos on 3 Nov 2016
what if we have two numbers? Lets say 50% probability to get a=0.05 and b= -0.05
Sorry I am a very beginner in MATLAB
Nikolas
Walter Roberson on 3 Nov 2016
AB = [a,b];
AB( randi([1 2]) )

Sean de Wolski on 7 Dec 2011
f = X(find(rand<cumsum(P),1,'first'))

#### 1 Comment

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.

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.

#### 1 Comment

Sepehr Saadatmand on 11 Oct 2019
That was what I was looking for. Thank you !