Non overlapping randomly located circles

Viewed 6523

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.

4 Answers

Although this is an old post, and because I faced the same problem before I would like to share my solution, which uses anonymous functions: https://github.com/davidnsousa/mcsd/blob/master/mcsd/cells.m . This code allows to create 1, 2 or 3-D cell environments from user-defined cell radii distributions. The purpose was to create a complex environment for monte-carlo simulations of diffusion in biological tissues: https://www.mathworks.com/matlabcentral/fileexchange/67903-davidnsousa-mcsd

A simpler but less flexible version of this code would be the simple case of a 2-D environment. The following creates a space distribution of N randomly positioned and non-overlapping circles with radius R and with minimum distance D from other cells. All packed in a square region of length S.

function C = cells(N, R, D, S)
  C = @(x, y, r) 0;
  for n=1:N
    o = randi(S-R,1,2);
    while C(o(1),o(2),2 * R + D) ~= 0
      o = randi(S-R,1,2);
    end
    f = @(x, y) sqrt ((x - o(1)) ^ 2 + (y - o(2)) ^ 2);
    c = @(x, y, r) f(x, y) .* (f(x, y) < r);
    C = @(x, y, r) + C(x, y, r) + c(x, y, r);
  end
  C = @(x, y) + C(x, y, R);
end

where the return C is the combined anonymous functions of all circles. Although it is a brute force solution it is fast and elegant, I believe.

Related