Selecting a "random" element from an array with each element having it's own weighting

Hi,
I am trying to write code that will permit me to select a "random" element from an array with each element having it's own weighting.
For example, assume array A = [1;2;3;4], where there is a 10% chance for 1, 20% chance for 2, 30% chance for 3 and 40% chance for 4 to be chosen.
I suppose I could just have number 2 added twice, number 3 three times and 4 four times, but trying to find something more robust since the data I'm working with is very large.
How would I go about writing this code?
Thanks

 Respuesta aceptada

A=[1,2,3,4];
p=[10 20 30 40];
c=cumsum(p);
[~,r]=histc(rand(1,1e6),[0 c/c(end)]); % generate 1e6 numbers
r=A(r);
% Check
histogram(r)

7 comentarios

So how would I actually take a random sample from A?
Bruno Luong
Bruno Luong el 26 de En. de 2021
Editada: Bruno Luong el 26 de En. de 2021
It's "r" 1e6 random samples from A.
I just need 1 random sample though
Change 1e6 in the code to 1 or to whatever the number of samples you wish.
That's great, thanks for clarifying!
What if I now have a requirement that means only the 3rd and 4th element can be selected? Preferably without having to change the % probability value of each (or recalculating the CDF again).

Iniciar sesión para comentar.

Más respuestas (1)

Jeff Miller
Jeff Miller el 26 de En. de 2021
Editada: Jeff Miller el 26 de En. de 2021
% Wts is your vector of weights.
Wts = Wts / sum(Wts); % make sure they sum to 1
cumPrs = cumsum(Wts); % cumPr is the cumulative probability of selecting each vector position or smaller
r = rand; % a random number between 0 and 1
randVecPos = find(cumPrs>r,1); % select this random vector position from your array

4 comentarios

A=[1,2,3,4];
Wts = [0.1,0.4,0.3,0.2];
cumPrs = cumsum(Wts);
r = rand;
randVecPos = find(r>cumPrs,1)
So if I assume 1 has 10% chance of being selected, 2 has 40% chance, etc.
If I use above code I always get 1 as the value for randVecPos
sorry, that should be cumPrs>r
Bruno Luong
Bruno Luong el 26 de En. de 2021
Editada: Bruno Luong el 26 de En. de 2021
This code is buggy, it returns empty with 10% chance.
Need to put 0 in front of the array of FIND command as with my code.

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Productos

Versión

R2020b

Preguntada:

el 26 de En. de 2021

Comentada:

el 7 de Feb. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by