# Random sampling with imposed condition

13 views (last 30 days)
Sina Sadeghi on 17 Feb 2020
Edited: Ajay Pattassery on 21 Feb 2020
I want to use random sampling to generate the x, y, and z coordinates of 10 particles in a (10*3) matrix in such a way that the distance between each pair of particles not to be less than 1. The formula for the distance between particles i and j is defined by distance=((xi-xj )^2+(yi-yj )^2+(zi-zj )^2 )^0.5 . I really appreciate if anyone can help me.
##### 2 CommentsShowHide 1 older comment
Sina Sadeghi on 17 Feb 2020
In the real problem, I have 6400 particles for which I nead to generate random x,y,z coordinates between 0 and 20. The minimum distance between each pair of particles should be 1 and the maximum distance should be 20*√3.

Sign in to comment.

### Answers (1)

Ajay Pattassery on 20 Feb 2020
Edited: Ajay Pattassery on 21 Feb 2020
I assume you want the samples to be generated from a uniform distribution in the range from 0 to 20.
You could use the reduction method to generate data samples of the desired constraint. That is, generate 10 samples and check whether the samples comply with the desired condition. If not, generate additional samples until the conditions are met.
numberOfSamples = 10;
randomSamples = 20*rand(numberOfSamples,3);
validPoints = reductionMethod(randomSamples);
while(size(validPoints,1) < numberOfSamples)
newPointsNeeded = numberOfSamples - size(validPoints,1);
newPoints = 20*rand(newPointsNeeded,3);
newSampleSpace = [validPoints;newPoints];
validPoints = reductionMethod(newSampleSpace);
end
function validPoints = reductionMethod(randomSamples)
distanceAmongPts = squareform(pdist(randomSamples));
distanceAmongPts(distanceAmongPts == 0) = 20*sqrt(3); % Do not want to consider the distance between that point and itself
wrongDist = (distanceAmongPts < 1);
wrongPoint = sum(wrongDist,2) > 0;
randomSamples(wrongPoint,:) = [];
validPoints = randomSamples;
end
The above algorithm samples points from uniform distribution but I do not think it is scalable to 6400 points. The maximum I saw is around 1000 points. I think some improvements can be done in the above algorithm in the removing section of points less than unit distance apart.
Alternatively,
You can think of the 20x20x20 surface equally divided into 8000 cubes. And from the center of those cubes, select 6400 cube centers.
x = 0.5:19.5; %Since 20 units is the maximum, the cube center will be (.5,.5,.5),(1.5,0.5,.5) etc
y = 0.5:19.5;
z = 0.5:19.5;
centers = combvec(x,y,z); %Center of all the possible cubes
centerPoints = randperm(8000,6400); % Randomly select 6400 integers out of 8000
randomCenters = centers(:,centerPoints); %Retrieve the corresponding centers
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

R2018b

### Community Treasure Hunt

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

Start Hunting!