Generate random binary sequence with a specific ratio

为君一笑 提交于 2021-01-27 21:00:58

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/30922204/generate-random-binary-sequence-with-a-specific-ratio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!