我编辑了一个我在网上找到的代码,可以帮助我根据它们之间的最小距离以某种方式在图表上绘制分数
这是我到目前为止的代码
x(1)=rand(1)*1000; %Random coordinates of the first point
y(1)=rand(1)*1000;
minAllowableDistance = 30; %IF THIS IS TOO BIG, THE LOOP DOES NOT END
numberOfPoints = 300; % Number of points equivalent to the number of sites
keeperX = x(1); % Initialize first point
keeperY = y(1);
counter = 2;
for k = 2 : numberOfPoints %Dropping another point, and checking if it can be positioned
done=0;
trial_counter=1;
while (done~=1)
x(k)=rand(1)*1000;
y(k)=rand(1)*1000;
thisX = x(k); % Get a trial point.
thisY = y(k);
% See how far is is away from existing keeper points.
distances = sqrt((thisX-keeperX).^2 + (thisY - keeperY).^2);
minDistance = min(distances);
if minDistance >= minAllowableDistance
keeperX(k) = thisX;
keeperY(k) = thisY;
done=1;
trial_counter=trial_counter+1;
counter = counter + 1;
end
if (trial_counter>2)
done=1;
end
end
end
end
所以这段代码工作正常,但是如果积分高于600,matlab就会冻结。问题已经完成,不再添加任何点,所以matlab一遍又一遍地完成工作。所以我需要找到一个方法,当trial_counter大于2时,找到一个空的空间并在那里定居。
如果第三次不适合,则trial_counter用于放弃一个点。 谢谢
答案 0 :(得分:2)
由于trial_counter=trial_counter+1;
仅在if minDistance >= minAllowableDistance
内调用,因此如果minDistance < minAllowableDistance
(例如,如果您的现有点非常密集),您将很容易进入无限循环。
如何执行此操作取决于您的限制,但如果您在设定范围内查看整数点,则可能将点保留为二进制图像,并使用bwdist
来计算距离变换,然后选择一个可接受的点。因此,每次迭代都是(其中BW
是您存储的“图像”/ 2D二进制矩阵,其中1是选定的点):
D = bwdist(BW);
maybe_points = find(D>minAllowableDistance); % list of possible locations
n = randi(length(maybe_points)); % pick one location
BW(maybe_points(n))=1; % add it to your matrix
(然后添加一些检查,如果你找不到循环退出的任何允许点)