Asked by Ayman Alotaibi
on 10 Mar 2018

We simulate this experiment by generating a logical array of

length N, with 1 (true) for "heads" and 0 (false) for "tails".

The problem is to generate the right number of 1s and 0s, so that

the percentage of 1s is p (60%). We shall do so in two ways.

N=1000; // number of coin tosses

p=0.6; // bias: percentage of 1s in the array

Method 1

Generate N observations from a uniform distribution on [0,1].

Threshold these observations at p. The resulting logical array

will have

1 if an observation was < p,

0 otherwise.

Answer by Roger Stafford
on 10 Mar 2018

Accepted Answer

Here's another way. Let there be N1 trues and N0 falses.

x = [repmat(true,1,N1),repmat(false,1,N0)];

x = x(randperm(N1+N0));

Image Analyst
on 10 Mar 2018

Of course it does. Here's my proof:

N1 = 60;

N0 = 40;

x = [repmat(true,1,N1),repmat(false,1,N0)];

x = x(randperm(N1+N0));

numOnes = sum(x) % Will say 60

Now it's your turn to give your proof that it DOES NOT work.

Ayman Alotaibi
on 10 Mar 2018

can I get the sum of zeros too ? like numZeros, so it gives 40? or should I do numOnes - X ?

Ayman Alotaibi
on 10 Mar 2018

I did this code at the bottom of code, and it worked

numZeros = length(zeros(1, N - numberOfOnes)) ;

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 4 Comments

## James Tursa (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/387432-generate-n-observations-from-a-uniform-distribution-on-0-1-and-compare-it-to-a-threshold#comment_543894

## Ayman Alotaibi (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/387432-generate-n-observations-from-a-uniform-distribution-on-0-1-and-compare-it-to-a-threshold#comment_543896

## Ayman Alotaibi (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/387432-generate-n-observations-from-a-uniform-distribution-on-0-1-and-compare-it-to-a-threshold#comment_543897

## Ayman Alotaibi (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/387432-generate-n-observations-from-a-uniform-distribution-on-0-1-and-compare-it-to-a-threshold#comment_543898

Sign in to comment.