how to create a list of random number with a minimum difference between each number?
11 views (last 30 days)
I am trying to create a list of 'n' random numbers within a range(1,m) and the difference between adjacent numbers need to be at least 'd'.
The list needs to be sorted and no repetion allowed.
I can do the same in python using
% r = m - ((m - 1) * (n - 1))
% = 30 - ((3-1) * (6-1)) = 30 - 2*5 = 20
%[(d-1)*i + x for i, x in enumerate(sorted(random.sample(range(r), n)))]
print([2*i + x for i, x in enumerate(sorted(random.sample(range(20), 6)))])
>>[2, 5, 14, 20, 24, 28]
In the above code, I am trying to generate a sorted list of 6 random numbers from 0-30, with a minimum difference between each adjacent element of at least 3.
Can some one plese suggest me how can I do something similar in matlab?
David Hill on 2 Aug 2022
Edited: David Hill on 2 Aug 2022
You can brute force it.
m=200;%randomn numbers between 1-200
a=randi(m,100000,n);%make sifficiently large
randNums=a(f,:);%rows of array having randomn numbers with adjacent elements being at least d apart