Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

matlab - Non overlapping randomly located circles

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're happy with brute-forcing, consider this solution:

N = 60;                        % number of circles
r = 0.5;                       % radius
newpt = @() rand([1,2]) * 10;  % function to generate a new candidate point

xy = newpt();  % matrix to store XY coordinates
fails = 0;     % to avoid looping forever
while size(xy,1) < N
    % generate new point and test distance
    pt = newpt();
    if all(pdist2(xy, pt) > 2*r)
        xy = [xy; pt];  % add it
        fails = 0;      % reset failure counter
    else
        % increase failure counter,
        fails = fails + 1;
        % give up if exceeded some threshold
        if fails > 1000
            error('this is taking too long...');
        end
    end
end

% plot
plot(xy(:,1), xy(:,2), 'x'), hold on
for i=1:size(xy,1)
    circle3(xy(i,1), xy(i,2), r);
end
hold off

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...