How to pick a value according to its probability

56 vues (au cours des 30 derniers jours)
Steven
Steven le 7 Déc 2011
Commenté : Real User le 28 Avr 2023
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
  4 commentaires
Walter Roberson
Walter Roberson le 3 Nov 2016
AB = [a,b];
AB( randi([1 2]) )
PANTHAGADA ANIL KUMAR
PANTHAGADA ANIL KUMAR le 16 Avr 2020
how to select an element with least probablility

Connectez-vous pour commenter.

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (3)

Jonathan
Jonathan le 3 Sep 2018
Modifié(e) : Jonathan le 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.
  4 commentaires
krishna teja
krishna teja le 20 Avr 2020
searched a lot for this kind of function
Real User
Real User le 28 Avr 2023
randsample() seems to require Statistics and Machine Learning Toolbox

Connectez-vous pour commenter.


Steven Lord
Steven Lord le 16 Avr 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.

Mendi
Mendi le 9 Juil 2021
The fastest one (100ns-200ns):
function [idx] = get_random_choice(p)
% Random choice with probability
% Example: get_random_choice([0.2,0.7,0.1])
N=length(p); idx=1; cump=0;
r=rand;
while(idx<N)
cump=cump+p(idx);
if(cump>r),break,else,idx=idx+1;end
end
end

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by