top of page

QA0009

Mohd Faisal Ansari IITJ in researchgate.net asked how to generate random numbers within given an input range1, but adjacently spaced at least another input range2<range1.

clear all;close all;clc

% your code

spacing=10;
n=20;
R=[0 500];
z=rand(n,1)*range(R)+min(R)

 

% may generate consecutive numbers closer than required spacing
 

nonzeros(abs(diff(z))<spacing)

 

% 1.- exhaustive spacing

z=randi([1 R(end)],n,1)*spacing

% non-exhaustive or quick check

% there are no consecutive numbers closer than spacing
 

nonzeros(abs(diff(z))<spacing)

% exhaustive check


nL=nchoosek([1:n],2);
nonzeros(abs(diff(z(nL)'))<spacing)

% now all pairs have distance>spacing

A slightly different problem would be to generate random numbers with difference greater than spacing, but only imposing such spacing between adjacent numbers.

bottom of page