Generate N observations from a uniform distribution on [0,1] and compare it to a threshold

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.

4 Comments

What have you done so far? What specific problems are you having with your code? Have you looked at the doc for the rand( ) function?
I’ll upload what I’ve done Give me few minutes plz
percentageOfOnes = p;
numberOfOnes = (N * percentageOfOnes );
signal = [ones(1, numberOfOnes), zeros(1, N - numberOfOnes)]; signal = signal(randperm(length(signal))); numOnes = sum(signal);
but this only gives u sum of ones, how can I have two signal with sum all ones, and sum all zeros

Sign in to comment.

 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));

4 Comments

I tried urs it won’t give me the result of all 1s 60% and 0s %40
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.
can I get the sum of zeros too ? like numZeros, so it gives 40? or should I do numOnes - X ?
I did this code at the bottom of code, and it worked
numZeros = length(zeros(1, N - numberOfOnes)) ;

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!