Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non overlapping randomly located circles

Tags:

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

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.

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])

Thank you.

like image 804
Matilde Avatar asked Mar 23 '16 11:03

Matilde


1 Answers

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.

code example:

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

*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).

output example

like image 54
ibezito Avatar answered Oct 12 '22 10:10

ibezito