필터 지우기
필터 지우기

Randomly choosing one of two options with specified probability

조회 수: 3 (최근 30일)
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
Ameer Hamza
Ameer Hamza 2020년 4월 8일
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 2020년 4월 9일
OK, I understood, Thanx for the explaination

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 4월 8일
편집: Ameer Hamza 2020년 4월 8일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by