# Find n random points with a minimum distance r inside a 2D rectangular box

108 views (last 30 days)

Show older comments

##### 0 Comments

### Answers (3)

John BG
on 12 Feb 2017

Edited: John Kelly
on 17 Feb 2017

Hi Jaydeep

just completed a couple functions that may help with your question

1.

download the functions scatter_points7.m and scatter_points_saturate.m

from

2.

run this

[X,Y,Nmax,Dmatrix]=scatter_points7

3.

key in the menu the rectangle size, the amount of points you want and the minimum distance.

4.

scatter_points7 returns:

X Y coordinates of the random points

Nmax the maximum amount of points that would fit in the rectangle if placing them orderly.

Dmatrix the distances between all combinations of points.

5.

Check the minimum distance requirement is met with

% test 1

Ap=20;L=combinator(Ap,2,'c');

relD2=((X(L(:,2))-X(L(:,1))).^2+(Y(L(:,2))-Y(L(:,1))).^2).^.5

R0=200;find(relD2<R0)

=

Empty matrix: 1-by-0

or

% test 2

Ap=20;L2=combinator(Ap,2);

D2=Dmatrix+NaN*eye(Ap);

R0=200;D2(D2<R0)

=

Empty matrix: 0-by-1

.

'

6.

Now try this

[X,Y,Nmax,Dmatrix]=scatter_points_saturate(2000,2000,200)

.

.

to know the amount of points (below Nmax) actually generated

numel(X)

if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?

To any other reader, please if you find this answer of any help solving your question,

please click on the thumbs-up vote link,

thanks in advance

John BG

##### 0 Comments

Jan
on 12 Feb 2017

Edited: Jan
on 21 Feb 2017

See the very similar question https://www.mathworks.com/matlabcentral/answers/322431-randompoints-condition-distance.

function [X, Y, D] = GetPointsRandom(nWant, XWidth, YWidth, MinDist)

X = zeros(nWant, 1);

Y = zeros(nWant, 1);

dist_2 = MinDist ^ 2; % Squared once instead of SQRT each time

iLoop = 1; % Security break to yoid infinite loop

nValid = 0;

while nValid < nWant && iLoop < 1e6

newX = XWidth * rand;

newY = YWidth * rand;

if all(((X(1:nValid) - newX).^2 + (Y(1:nValid) - newY).^2) >= dist_2)

% Success: The new point does not touch existing points:

nValid = nValid + 1; % Append this point

X(nValid) = newX;

Y(nValid) = newY;

end

iLoop = iLoop + 1;

end

% Throw an error, if the area is filled too densely:

if nValid < nWant

error('Cannot find wanted number of points in %d iterations.', iLoop)

end

if nargout > 2

% D = pdist([X, Y]); % Faster with statistics toolbox

D = sqrt(bsxfun(@minus, X, X.') .^ 2 + bsxfun(@minus, Y, Y.') .^ 2);

end

end

##### 0 Comments

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!