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

generate non-consecutive samples

Ray Phan
Jul 02, 2015
<p>A solution in MATLAB (perhaps inelegant) could be something like this:</p> <pre><code>N = 10; k = 4; out = zeros(1,k); vec = 1 : N; for idx = 1 : k ind = randi(numel(vec), 1); left = max(ind-1, 1); right = min(numel(vec), ind+1); out(idx) = vec(ind); to_remove = ind; if vec(left) == vec(ind)-1 to_remove = [to_remove left]; end if vec(right) == vec(ind)+1 to_remove = [to_remove right]; end vec(to_remove) = []; end </code></pre> <p>We first declare <code>N</code> and <code>k</code>, then declare an output array of zeroes that is <code>k</code> long. We then generate a sampling vector <code>vec</code> that goes from 1 up to as <code>N</code> initially. Next, for each value we want to place into the output, we generate a random position to sample from the vector, then take a look at the position from the left and from the right... ensuring that we are within the boundaries of the array. Also, we <strong>only</strong> remove to the left or right if the value at the left of the index to remove and also the right are equal to each other (thanks beaker!)</p> <p>We use this location and sample from this vector, place the value at this location to the output, then remove the indices in this vector that are to the left, to the right, and the actual index itself from this vector. This removes the possibility of sampling from those values again. We repeat this until we run out of values to place in the output.</p> <p>Here are a few of trial runs:</p> <pre><code>&gt;&gt; out out = 9 7 1 5 &gt;&gt; out out = 7 1 4 10 &gt;&gt; out out = 10 8 1 6 &gt;&gt; out out = 10 4 8 1 </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31059311/generate%20non-consecutive%20samples/31059636">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus