nPoints = 37;
lim = [100,1900];
minDist = 200;
xy = nan(nPoints,2);
c = 0;
while any(isnan(xy(:))) && c<(nPoints*100)
xy(isnan(xy)) = rand(1,sum(isnan(xy(:)))) * (lim(2)-lim(1)) + lim(1);
[~,isTooClose] = find(triu(squareform(pdist(xy)) < minDist,1));
xy(isTooClose,:) = NaN;
c = c+1;
end
if any(isnan(xy(:)))
error('The while-loop gave up. There are %d coordinates with missing values.',sum(isnan(xy(:,1))))
end
fprintf('%d number of attempts.\n', c)
distances = squareform(pdist(xy));
fprintf('Min distance = %.2f\n', min(distances(distances~=0)))
figure()
plot(xy(:,1),xy(:,2), 'ks', 'MarkerSize', 10)
grid on
6 Comments
Bruno Luong (view profile)
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/482247-how-to-genetate-random-number-under-constraint#comment_750158
Muhammad Nabeel Hussain (view profile)
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/482247-how-to-genetate-random-number-under-constraint#comment_750162
Adam (view profile)
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/482247-how-to-genetate-random-number-under-constraint#comment_750166
Bruno Luong (view profile)
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/482247-how-to-genetate-random-number-under-constraint#comment_750182
Adam Danz (view profile)
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/482247-how-to-genetate-random-number-under-constraint#comment_750183
Adam Danz (view profile)
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/482247-how-to-genetate-random-number-under-constraint#comment_750185
Sign in to comment.