MATLAB Answers

select random number from an array with probabilities

72 views (last 30 days)
Margherita Premoli
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 Comment

Adam
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
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

Show 1 older comment
Margherita Premoli
Margherita Premoli on 21 Feb 2020
sorry to bother you again but why do we need the cumulative probability?
Sky Sartorius
Sky Sartorius on 21 Feb 2020
For any probability distribution or set of probabilities (that add up to 1), the cumulative distribution function (CDF) will yield a result between 0 and 1. The random number generator also returns numbers between 0 and 1, so by mapping that to the output of the CDF, you can generate your values at the desired distribution. You can visualize:
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)];
plot(0:3,cp,'ok')
xlabel('Index')
ylabel('Cum. prob.')
figure
plot(cp,0:3)
xlabel('r')
ylabel('Index (take ceil of result)') % Ceil is also why find is 'r>cp' and 'last'.
title('Reverse CDF lookup')

Sign in to comment.

Tags


Translated by