Reputation: 55
I have to create highway scenario in MATLAB. I have to generate random points (i.e. vehicles) on highway. By using randn() command, random points are overlapping on each other. I want to generate random points such that a minimum distance between random points is maintained.
Could anybody help me in generating this kind of scenario..
Upvotes: 3
Views: 2241
Reputation: 1051
This is not an elegant solution, but it satisfies your minimum distance constraint.
% Highway dimensions
lx = 1000;
ly = 1000;
% Minimum distance
d = 100;
% Number of points to generate
n = 50;
points = [rand(1, 2) .* [lx ly]];
d2 = d ^ 2;
% Keep adding points until we have n points.
while (size(points, 1) < n)
% Randomly generate a new point
point = rand(1, 2) .* [lx ly];
% Calculate squared distances to all other points
dist2 = sum((points - repmat(point, size(points, 1), 1)) .^ 2, 2);
% Only add this point if it is far enough away from all others.
if (all(dist2 > d2))
points = [points; point];
end
end
plot(points(:,1), points(:,2), 'o')
Upvotes: 1
Reputation: 20080
You might consider Poisson disc (a.k.a. disk) sampling. Basically, Poisson-disc sampling produces points that are tightly-packed, but no closer to each other than a specified minimum distance, resulting in a more natural pattern.
My matlab is rusty, sorry, no code, but links
http://www.cs.sandia.gov/~samitch/papers/cccg-present.pdf
https://www.jasondavies.com/poisson-disc/
Upvotes: 2