Generate A Sequence of 25 Independent Bernoulli RVs with p = .8?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Steven
el 29 de Sept. de 2014
Comentada: Steven
el 30 de Sept. de 2014
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!
0 comentarios
Respuesta aceptada
SK
el 30 de Sept. de 2014
Editada: SK
el 30 de Sept. de 2014
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.
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!