正如 Amro 评论的那样,找到正确的分数顺序是困难的部分。这个功能够用吗?
function [idx] = Polyfy(x, y)
% [idx] = Polyfy(x, y)
% Given vectors x and y that contain pairs of points, find the order that
% joins them into a polygon. fill(x(idx),y(idx),'r') should show no holes.
%ensure column vectors
if (size(x,1) == 1)
x = x';
end
if (size(y,1) == 1)
y = y';
end
% vectors from centroid of points to each point
vx = x - mean(x);
vy = y - mean(y);
% unit vectors from centroid towards each point
v = (vx + 1i*vy)./abs(vx + 1i*vy);
vx = real(v);
vy = imag(v);
% rotate all unit vectors by first
rot = [vx(1) vy(1) ; -vy(1) vx(1)];
v = (rot*[vx vy]')';
% find angles from first vector to each vector
angles = atan2(v(:,2), v(:,1));
[angles, idx] = sort(angles);
end
这个想法是找到点的质心,然后找到从质心到每个点的向量。您可以将这些向量视为三角形的边。多边形由一组三角形组成,其中每个向量仅用作“左”和“右”一次,并且没有跳过任何向量。这归结为按质心周围的角度对向量进行排序。
我选择通过将向量归一化为单位长度,选择其中一个作为旋转向量,然后旋转其余的来做到这一点。这让我可以简单地使用 atan2 来找到角度。可能有一种更快和/或更优雅的方式来做到这一点,但我对三角身份感到困惑。最后,对这些角度进行排序可为点提供正确的顺序以形成所需的多边形。
这是测试功能:
function [x, y] = TestPolyArea(N)
x = rand(N,1);
y = rand(N,1);
[indexes] = Polyfy(x, y);
x2 = x(indexes);
y2 = y(indexes);
a = polyarea(x2, y2);
disp(num2str(a));
fill(x2, y2, 'r');
hold on
plot(x2, y2, '.');
hold off
end
通过 N = 100 左右可以得到一些非常狂野的图片!