Randomly choosing one of two options with specified probability

3 visualizaciones (últimos 30 días)
I have two subroutines to be executed, one with probability p1 and another with probability p2 s.t. p1+p2=1, i am approching the problem in following methods:
say p1=0.6, p2=0.4, i need to perform the selection between 2 subroutine 10 times
  1. Use function: out = randsrc(1,10,[1,2;0.6,0.4]); then choose routine 1 corresponding to 1 in output matrix and routine 2 corresponding to 2 in output matrix
here i'm getting output1: 2 1 2 2 1 2 1 2 1 1
executing again it is giving out: 1 1 2 2 2 2 1 2 1
expected output was number-1, 6-times and number-2, 4-times, but the output is not as expected.
2. use function: s = randsample([1,2],10,true,[0.6,0.4]);
3. use routine:
s=[];
for i=1:10
c = rand
if c<=0.6
select = 2;
else
select = 1;
end
s = [s,select];
end
method 2 and 3 are also giving the results as of method 1, can anyone help me to figure out the reason? or interpret the results as how they are following probability? or some other possible method to solve this problem.
  4 comentarios
Ameer Hamza
Ameer Hamza el 8 de Abr. de 2020
Shivani, the probability does not mean that the random numbers should be generated exactly in the proportion of probability density function. It just means that if you generate a very long series, the histogram of the generated numbers will approximately match the density function.
The "correct" depends on what you want to do. If your goal is just to follow the probability p1 and p2 in your question, then your code is already correct. But if your goal is to exactly run the two tasks in the proportion specified by p1 and p2 and the approach is given in my answer will be correct.
Shivani Agarwal
Shivani Agarwal el 9 de Abr. de 2020
OK, I understood, Thanx for the explaination

Iniciar sesión para comentar.

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 8 de Abr. de 2020
Editada: Ameer Hamza el 8 de Abr. de 2020
If you always want to keep fixed numbers of 1s and 2s, they try something like this
N = 10;
p2 = 0.4;
out = ones(1,10);
idx = randperm(10, floor(N*p2));
out(idx) = 2;
Result:
out =
2 1 2 2 2 1 1 1 1 1
out =
1 2 2 1 1 1 1 2 2 1
out =
1 2 1 2 1 2 1 1 2 1

Más respuestas (0)

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by