How to choose an element from a vector with not equal probabilities?

3 views (last 30 days)
I'm working with Monte Carlo simulations of polymers and I need to choose elements from a vector which have a probability to be chosen proportional to the value of the element. For example if I have the following vector:
A=[10 70 30 100];
The probability of every element to be chosen is the following:
P=[1/20 7/20 3/20 1/2]; %P(i)=A(i)/sum(A)
I wanted to know if there is any command in MATLAB or optimized method to choose an specific element, given the probability vector P. I'm using a function made by myself that works well but is quite slow and in high numbers of particles it's insuming a lot of time. The function I'm using is following:
function [sel] = randp(A,upp) %Here upp=sum(A)
r=floor(rand()*upp)+1; %I choose a random point between the extended array
f=0;
f2=A(1);
for i=1:length(A)
if f<r && r<=f2
sel=i;
break
else
f=f2;
f2=f2+A(i+1);
end
end
Thank you in advance for any help. I hope I made myself clear. And sorry for any grammar mistakes, my english is a bit rusty

Accepted Answer

Torsten
Torsten on 6 Jun 2022
A=[10 70 30 100];
P=[0,cumsum(A)/sum(A)]
P = 1×5
0 0.0476 0.3810 0.5238 1.0000
R = rand(10,1)
R = 10×1
0.5094 0.6495 0.5746 0.8497 0.0329 0.9060 0.5132 0.0183 0.3107 0.9432
Y = discretize(R,P)
Y = 10×1
3 4 4 4 1 4 3 1 2 4
Rand = A(Y)
Rand = 1×10
30 100 100 100 10 100 30 10 70 100

More Answers (1)

Walter Roberson
Walter Roberson on 6 Jun 2022
https://www.mathworks.com/help/stats/randsample.html using the w parameter.
If you do not have that toolbox then there are ways to vectorize the approach you are taking.

Categories

Find more on Energy Production in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!