필터 지우기
필터 지우기

Generate A Sequence of 25 Independent Bernoulli RVs with p = .8?

조회 수: 1 (최근 30일)
Steven
Steven 2014년 9월 29일
댓글: Steven 2014년 9월 30일
I have a question that asks me to generate a sequence of 25 independent Bernoulli RVs where p = .8. I want to see how many random numbers are needed to achieve this.
Here's what I have gathered so far ...
X = rand(1); Y = ( X <= p ); % Will generate Y = 0 if false, Y = 1 if true.
I want to create a vector with all of the Y values of 0s and 1s and have the program terminate after 25 1's have been generated. Then I want to find out the length of the entire vector with 0's and 1's.
Any help you can provide me would be GREATLY appreciated!

채택된 답변

SK
SK 2014년 9월 30일
편집: SK 2014년 9월 30일
If you are not too concerned about efficiency, and I suspect that you are not, you could use a while loop.
p = 0.8;
Y(35,1) = false; % Create a column vector of 35 zeros
ones_count = 0;
i = 1;
while (ones_count < 25)
Y(i) = (rand <= p);
ones_count = ones_count + Y(i);
i = i + 1;
end
Y(i : end) = []; % Clear unused part of vector. A misleadingly simple operation.
number_of_rands = length(Y);
Of course, the initial allocation of 35 elements for Y may not be sufficient, but that is unlikely. Even if not sufficient, Matlab will create the new elements for you, albeit inefficiently, when you do Y(i) = ... for i > 35. In any case writing:
Y(i:end) = [];
Makes your code inefficient, so no point worrying about efficiency.

추가 답변 (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