Matlab:找到相同距离的x点

时间:2017-04-24 09:02:36

标签: matlab

我想绘制一些随机圆圈,以3到25之间的距离分隔。

因此,如果每个圆的半径为5,则它们的中心之间的距离必须在13到35之间。

这是我当前的代码,但不起作用:

ok=false;
while 1
    x = 100 * rand(100,1);
    y = 100 * rand(100,1);
    A = pdist2([x,y],[x,y]);
    test1 = (A > 3 + size*num_clusters);
    test2 = A < 30 + size*num_clusters;
    test3 = test1.*test2;
    num_clusters = 3;
    for i=1:length(x)
        sum(test3(i,:))
        if sum(test3(i,:)) > num_clusters
            logic = test3(i,:);
            logic = find(logic);
            logic = logic';
            x = x(logic);
            y = y(logic);
            ok=true;
            break
        end
        if ok
            break
        end
    end
    if ok
        break
    end
end

X(1:num_clusters,1) = x(1:num_clusters);
X(1:num_clusters,2) = y(1:num_clusters);

1 个答案:

答案 0 :(得分:0)

这对您的解决方案略有不同,但效果很好。您可以按原样在matlab中运行它并查看结果。让我知道

   patchCircle = @(diam,X,Y,spec) arrayfun(@(x,y) patch(sin(-pi:.1:pi).*diam +x,cos(-pi:.1:pi).*diam+y,spec{:}),X,Y); % patches a circle of diameter DIAM, centered in x,y

radius_circles                 = 2; 
min_distance_between_circles   = 8; 
max_idstance_between_circles   = 30;
num_circles                    = 6; 
size_area                      = 40; % size of the area where the circles are
maximumNumberOfIterations      = 1000; % maximum mumber of iterations to find each new circle
exitSearch = false;

circles = size_area * rand(1,2);
for i_circle = 1 : num_circles - 1
    j = 1;
    keepLooping = true;
    while keepLooping
        j = j+1;
        if j > maximumNumberOfIterations
            fprintf('maximumNumberOfIterations reached. Increase area size or dicrease number of circles\n');
            keepLooping = false;
            exitSearch = true;
        end
        newCoords = size_area * rand(1,2);
        distances = pdist2(circles,newCoords);
        isMoreThanMinSize = distances > (min_distance_between_circles + radius_circles*2);
        isLessThanMaxSize = distances < (max_idstance_between_circles + radius_circles*2);
        if all(isMoreThanMinSize & isLessThanMaxSize)
            keepLooping = false;
            circles(i_circle,:) = newCoords;
            fprintf('circle n° %d of %d found\n',i_circle+1,num_circles)
        end
    end
    if exitSearch
       break 
    end
end
%% PLOT RESULTS
    cla; patchCircle(radius_circles,circles(:,1),circles(:,2),{'r','facealpha',.2})
    ylim([0 size_area]+[-1 1]*radius_circles)
    xlim([0 size_area]+[-1 1]*radius_circles)

显然,如果您在太小的空间中寻找太多的圆圈或大圆圈,搜索会在经过一定次数的迭代后停止。