非重叠的随机定位的圆 [英] Non overlapping randomly located circles
问题描述
我需要生成固定数量的不重叠的随机分布的圆.我可以显示用这段代码随机放置的圆圈(在这种情况下为20)
I need to generate a fixed number of non-overlapping circles located randomly. I can display circles, in this case 20, located randomly with this piece of code,
for i =1:20
x=0 + (5+5)*rand(1)
y=0 + (5+5)*rand(1)
r=0.5
circle3(x,y,r)
hold on
end
但是圆圈重叠,我想避免这种情况.这是由以前的用户使用Mathematica > https://mathematica.stackexchange.com/questions/69649/来实现的generate-nonoverlapping-random-circles ,但是我正在使用MATLAB,我想坚持下去.
however circles overlap and I would like to avoid this. This was achieved by previous users with Mathematica https://mathematica.stackexchange.com/questions/69649/generate-nonoverlapping-random-circles , but I am using MATLAB and I would like to stick to it.
为了重现性,这是函数circle3,我正在使用它来绘制圆圈
For reproducibility, this is the function, circle3, I am using to draw the circles
function h = circle3(x,y,r)
d = r*2;
px = x-r;
py = y-r;
h = rectangle('Position',[px py d d],'Curvature',[1,1]);
daspect([1,1,1])
谢谢.
推荐答案
,您可以保存所有先前绘制的圆的列表.后 随机化一个新的圆,以确保它不与先前绘制的圆相交.
you can save a list of all the previously drawn circles. After randomizing a new circle check that it doesn't intersects the previously drawn circles.
代码示例:
nCircles = 20;
circles = zeros(nCircles ,2);
r = 0.5;
for i=1:nCircles
%Flag which holds true whenever a new circle was found
newCircleFound = false;
%loop iteration which runs until finding a circle which doesnt intersect with previous ones
while ~newCircleFound
x = 0 + (5+5)*rand(1);
y = 0 + (5+5)*rand(1);
%calculates distances from previous drawn circles
prevCirclesY = circles(1:i-1,1);
prevCirclesX = circles(1:i-1,2);
distFromPrevCircles = ((prevCirclesX-x).^2+(prevCirclesY-y).^2).^0.5;
%if the distance is not to small - adds the new circle to the list
if i==1 || sum(distFromPrevCircles<=2*r)==0
newCircleFound = true;
circles(i,:) = [y x];
circle3(x,y,r)
end
end
hold on
end
*请注意,如果圆的数量相对于绘制x和y坐标的范围太大,则循环可能会无限运行. 为了避免出现这种情况,请相应地定义此范围(可以将其定义为nCircles的函数).
*notice that if the amount of circles is too big relatively to the range in which the x and y coordinates are drawn from, the loop may run infinitely. in order to avoid it - define this range accordingly (it can be defined as a function of nCircles).
这篇关于非重叠的随机定位的圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!