× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Generate random binary sequence with a specific ratio

Ray Phan
Jun 24, 2015
<p>You can approach this in one of two ways (à la Luis Mendo):</p> <h1>Approach #1 - Deterministic</h1> <p>If you know that you need <strong>exactly 500 ones and 500 zeroes</strong> 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 - <code>num_elements</code>) and extract 500 (or in general <code>round(ratio*num_elements)</code> where <code>ratio</code> is between <code>[0,1]</code>) of them. You'd then use these indices and set the locations in an initial zero vector to 1:</p> <pre><code>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; </code></pre> <h1>Approach #2 - Probabilistic</h1> <p>You can generate uniformly distributed random values from <code>[0-1]</code> and threshold with 0.5, or the <code>ratio</code>:</p> <pre><code>num_elements = 1000; ratio = 0.5; A = rand(num_elements, 1) &gt;= ratio; </code></pre> <p>This in a probabilistic sense fills each value in the vector with a 50% (or in general <code>ratio</code>) chance of making the value 0 and a 50% (or in general <code>1 - ratio</code>) chance of making the value 1.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30922204/Generate%20random%20binary%20sequence%20with%20a%20specific%20ratio/30922439">Stack Overflow</a>.</p>
comments powered by Disqus