MATLAB: How to similuate a coin flip with probablility p

probability

How do I simulate getting a result, either 0 or 1, with probability p. So if p=0.5 I should get an output of 0 half of the time, and 1 half of the time.

Best Answer

100 tosses with p=0.5.
x = round(rand(100,1));
If you want a probability other than p=0.5, then realize that rand() is uniform random number generator between [0,1], so you can assign the output of rand() accordingly. For example, for p=0.25:
y = zeros(100,1);
x = rand(100,1);
y(x<0.25) = 1;
Or if you just want to simulate the number of 0's or 1's in a certain number of trials. Say 100 for example. Here is a simulation of ten such experiments. Requires Statistics Toolbox.
R = binornd(100,0.5,10,1);
Related Question