mat
mat

Reputation: 2617

Generate random binary sequence with a specific ratio

I want to generate a random binary sequence with a ratio of 50%, that is, the same amounts of 0s and 1s. This is what I have so far:

length_sequence = 1000;
ratio = 0.5;
A = logical(randi([0 1],length_sequence,1));

The only problem is that I dont know how to set the ratio.

Upvotes: 2

Views: 154

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

The ratio can be interpreted as deterministic (you want 500 ones and 500 zeros in each realization of 1000 values) or as probabilistic (a realization may have more ones than zeros, but the ratio holds over a very large number of realizations).

Your code works for the probabilistic interpretation, so I'm assuming you mean the deterministic one. In that case, fill A with the zero and one values in any order (for example: first all ones, then all zeros), and then apply a random permutation:

length_sequence = 1000;
ratio = 0.5; %// interpreted as proportion of ones that there must be in any realization
A = zeros(1,length_sequence);
A(1:round(length_sequence*ratio)) = 1;
A = A(randperm(length_sequence));

Upvotes: 3

rayryeng
rayryeng

Reputation: 104484

You can approach this in one of two ways (à la Luis Mendo):

Approach #1 - Deterministic

If you know that you need exactly 500 ones and 500 zeroes for each time you create this vector, you can generate a set indices from 1 to 1000 (or in general from 1 to as many elements as you want - num_elements) and extract 500 (or in general round(ratio*num_elements) where ratio is between [0,1]) of them. You'd then use these indices and set the locations in an initial zero vector to 1:

num_elements = 1000;
ratio = 0.5; %// 50%
ind = randperm(num_elements, round(ratio*num_elements));
A = zeros(num_elements,1) == 1; %// Convert to logical
A(ind) = 1;

Approach #2 - Probabilistic

You can generate uniformly distributed random values from [0-1] and threshold with 0.5, or the ratio:

num_elements = 1000;
ratio = 0.5;
A = rand(num_elements, 1) >= ratio;

This in a probabilistic sense fills each value in the vector with a 50% (or in general ratio) chance of making the value 0 and a 50% (or in general 1 - ratio) chance of making the value 1.

Upvotes: 3

Related Questions