Search code examples
matlabprobabilitysampling

Randomly choosing one of two options with specified probability


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.

  1. use function: s = randsample([1,2],10,true,[0.6,0.4]);
  2. 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.


Solution

  • I suppose 10 specimens are not enough for representing the 60% / 40% distribution you are expecting.

    When dropping a coin 10 times, the probability for getting 5 heads and 5 tails is not so high.

    Try 1000000 values:

    out = randsrc(1, 1000000, [1,2;0.6,0.4]);
    

    Now the distribution should be very close to 60% / 40%:

    [sum(out==1), sum(out==2)]
    
    ans =
    
          599709      400291
    

    You can also use rand:

    x = rand(1, 1000000);
    [sum(x <= 0.6), sum(x > 0.6)]
    
    ans =
    
          600261      399739