Non overlapping randomly located circles

前端 未结 4 551
生来不讨喜
生来不讨喜 2020-12-21 07:02

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,

<         


        
4条回答
  •  悲哀的现实
    2020-12-21 07:30

    Slightly amended code @drorco to make sure exact number of circles I want are drawn

    nCircles = 20;
    circles = zeros(nCircles ,2);
    r = 0.5;
    c=0; 
    
    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 & c<=nCircles
        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;
            c=c+1
            circles(i,:) = [y x];
            circle3(x,y,r)
        end
    
    end
    hold on
    

    end

提交回复
热议问题