MATLAB: Pick a number from an array with a certain probability

inverse transform samplingprobabilityrandom number

Hi!
I have an array from 1 to 150 [1 2 3 …]
and the corresponding probability [0.001 0.003 0.002 …]
Now I'd like to pick a random number from the first array with taking into account the respective probability.
Has anyone an idea how to proceed?
Thanks!

Best Answer

If you can use pre-defined functions and you have Statistics and Machine Learning Toolbox, then you can use randsample(): https://www.mathworks.com/help/releases/R2020a/stats/randsample.html. Something like this
pop = 1:150;
prob = % probability values 1x150
y = randsample(pop, 1000, true, prob)
If you don't have the toolbox, then try following FEX packages:
Related Question