Non overlapping randomly located circles

前端 未结 4 552
生来不讨喜
生来不讨喜 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:21

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

提交回复
热议问题