我需要帮助来解决这个问题。我有随机生成的点(例如图片#1 ),我想用线连接它们(例如图片#2 )。线不能相交,连接后,连接点看起来应该是不规则区域。
%Generating random points
xn = randi([3 7],1,10);
yn = randi([3 6],1,10);
%Generated points
xn = [6,3,7,7,6,6,6,4,6,3];
yn = [5,3,4,3,3,6,5,4,6,3];
图片#1:
结果应该是这样的: 图片#2:
知道如何解决这个问题吗?
答案 0 :(得分:8)
我认为,对于一般情况,提出解决方案可能非常困难。但是,假设你的分数很“分散”,那么就有一个简单的解决方案。
如果您根据连接点和点云中心的矢量x轴上方的角度对点进行排序,那么:
P = [xn;yn]; %// group the points as columns in a matrix
c = mean(P,2); %// center point relative to which you compute the angles
d = bsxfun(@minus, P, c ); %// vectors connecting the central point and the dots
th = atan2(d(2,:),d(1,:)); %// angle above x axis
[st si] = sort(th);
sP = P(:,si); %// sorting the points
就是这样。绘制结果:
sP = [sP sP(:,1)]; %// add the first point again to close the polygon
figure;plot( sP(1,:), sP(2,:), 'x-');axis([0 10 0 10]);
如果几个点在点云的中心具有相同的角度,则此算法将失败。
一个包含20个随机点的例子:
P = rand(2,50);
答案 1 :(得分:4)
您可以调整another answer I gave中的代码来生成任意数量边的随机简单多边形。这里的区别在于您已经选择了一组点,因此隐含了您想要的边数(即与唯一点的数量相同)。这是代码的样子:
xn = [6,3,7,7,6,6,6,4,6,3]; % Sample x points
yn = [5,3,4,3,3,6,5,4,6,3]; % Sample y points
[~, index] = unique([xn.' yn.'], 'rows', 'stable'); % Get the unique pairs of points
x = xn(index).';
y = yn(index).';
numSides = numel(index);
dt = DelaunayTri(x, y);
boundaryEdges = freeBoundary(dt);
numEdges = size(boundaryEdges, 1);
while numEdges ~= numSides
if numEdges > numSides
triIndex = vertexAttachments(dt, boundaryEdges(:,1));
triIndex = triIndex(randperm(numel(triIndex)));
keep = (cellfun('size', triIndex, 2) ~= 1);
end
if (numEdges < numSides) || all(keep)
triIndex = edgeAttachments(dt, boundaryEdges);
triIndex = triIndex(randperm(numel(triIndex)));
triPoints = dt([triIndex{:}], :);
keep = all(ismember(triPoints, boundaryEdges(:,1)), 2);
end
if all(keep)
warning('Couldn''t achieve desired number of sides!');
break
end
triPoints = dt.Triangulation;
triPoints(triIndex{find(~keep, 1)}, :) = [];
dt = TriRep(triPoints, x, y);
boundaryEdges = freeBoundary(dt);
numEdges = size(boundaryEdges, 1);
end
boundaryEdges = [boundaryEdges(:,1); boundaryEdges(1,1)];
x = dt.X(boundaryEdges, 1);
y = dt.X(boundaryEdges, 2);
以下是生成的多边形:
patch(x,y,'w');
hold on;
plot(x,y,'r*');
axis([0 10 0 10]);
有两点需要注意:
TriRep
和DelaunayTri
类,在将来的MATLAB版本中可以删除这两个类,而不是delaunayTriangulation
类。