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

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 日

0 投票

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.

1 件のコメント

Steven
Steven 2014 年 9 月 30 日
Thank you so much! This makes sense!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2014 年 9 月 29 日

コメント済み:

2014 年 9 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by