How to choose an element from a vector with not equal probabilities?
6 views (last 30 days)
Show older comments
Tomás Romero Pietrafesa
on 6 Jun 2022
Commented: Tomás Romero Pietrafesa
on 6 Jun 2022
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
0 Comments
Accepted Answer
Torsten
on 6 Jun 2022
A=[10 70 30 100];
P=[0,cumsum(A)/sum(A)]
R = rand(10,1)
Y = discretize(R,P)
Rand = A(Y)
More Answers (1)
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.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!