生成具有特定比率的随机二进制序列 [英] Generate random binary sequence with a specific ratio

查看:45
本文介绍了生成具有特定比率的随机二进制序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个比率为50%的随机二进制序列,即0和1的数量相同.这是我到目前为止的内容:

  length_sequence = 1000;比率= 0.5;A =逻辑(randi([0 1],length_sequence,1)); 

唯一的问题是我不知道如何设置比率.

解决方案

该比率可以解释为确定性(您希望在每个1000个值的实现中都包含500个零和500个零)或>概率(一个实现可能比零多,但该比率保持着非常多的实现).

您的代码适用于概率解释,所以我假设您的意思是确定性的.在这种情况下,请以任意顺序将零和一值填充到 A 中(例如:首先是全1,然后是全零),然后应用随机置换:

  length_sequence = 1000;比率= 0.5;%//解释为任何实现中必须存在的比例A =零(1,length_sequence);A(1:round(length_sequence * ratio))= 1;A = A(randperm(长度序列)); 

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.

解决方案

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

这篇关于生成具有特定比率的随机二进制序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆