我是新来的,这是我的第一个帖子。我想知道是否有一种方法可以从100个随机点中计算所有可能的凸包。我已经创建了一个正确的代码,但是它在船体上给了我一个错误,并且该部分以下的所有内容都无法计算…换句话说,我想知道是否有一种方法可以在for循环中使用函数convhull而不会出现错误。
这里是代码
hold on
N=100;
Points = zeros(N,2);
for i=1:N
Points(i,1)= rand(1,1)*100;
Points(i,2)= rand(1,1)*100;
end
SortedX = sortrows(Points,1);
NewVertices = SortedX;
X = reshape(SortedX(:,1),2,[]);
X = X(:);
Y = reshape(SortedX(:,2),2,[]);
Y = Y(:);
plot(X,Y,'*');
while length(NewVertices)>=3
NewVertices = NewVertices(NewVertices~=0);
rowsNV = length(NewVertices(:,1));
NewVertices = reshape(NewVertices,rowsNV/2,2);
XNV = reshape(NewVertices(:,1),rowsNV/2,[]);
XNV = XNV(:);
YNV = reshape(NewVertices(:,2),rowsNV/2,[]);
YNV = YNV(:);
K = convhull(XNV,YNV);
plot(XNV(K),YNV(K),'r-');
for i=1:length(K)-1
NewVertices(K(i),1)=0;
NewVertices(K(i),2)=0;
end
end
这里是错误
Error using convhull
Error computing the convex hull. Not
enough unique points specified.
Error in test2 (line 28)
K = convhull(XNV,YNV);
Thanks in advance
co2ark5
这是在DAN的帮助下正确工作的最终代码
hold on
N=100;
Points = rand(N,2);
SortedX = sortrows(Points,1);
NewVertices = SortedX;
plot(SortedX(:,1),SortedX(:,2),'*');
while length(NewVertices)>=3
X=NewVertices(:,1);
Y=NewVertices(:,2);
K = convhull(X,Y);
plot(X(K),Y(K),'r-');
for i=1:length(K)-1
NewVertices(K(i),1)=0;
NewVertices(K(i),2)=0;
end
NewVertices = NewVertices(any(NewVertices,2),:);
end
该错误相当有表现力,您没有指定足够的点(即至少3个非共线点)。请解释一下你想用这段代码实现什么。
你什么时候得到这个错误?我想第一次循环时不会吧?在检查有超过3个点之后,你可能会立即删除更多的点,然后调用convhull,所以很有可能有少于3个点(这仍然忽略了共线的机会)。出现错误后,size(NewVertices)
是什么?
一些旁注:请在绘图之前解释整个重塑业务(可能会添加一些注释)。此外,Points
可以更快速、更简单地初始化:
Points = rand(N, 2);
编辑:从阅读你下面的评论,我很清楚,你的循环逻辑是错误的。我无法确切地弄清楚你是如何试图删除点来创建新的子集,在这个子集上找到船体,没有评论,我不知道你在做什么与reshape
,但我很确定你需要做的就是将你的循环的第一行移动到末尾,像这样:
while length(NewVertices)>=3
rowsNV = length(NewVertices(:,1));
NewVertices = reshape(NewVertices,rowsNV/2,2);
XNV = reshape(NewVertices(:,1),rowsNV/2,[]);
XNV = XNV(:);
YNV = reshape(NewVertices(:,2),rowsNV/2,[]);
YNV = YNV(:);
K = convhull(XNV,YNV);
plot(XNV(K),YNV(K),'r-');
for i=1:length(K)-1
NewVertices(K(i),1)=0;
NewVertices(K(i),2)=0;
end
NewVertices = NewVertices(NewVertices~=0);
end
这样你可以在检查点数后立即找到你的船体,而不是检查,然后删除点数,这就是为什么你的循环运行在1 - 2点。
非常感谢DAN,
首先我试着只改变你说的行,但它没有再次工作,因为我正在使用的重塑功能。然后我决定改变它们,我让它更简单,它确实工作!!
这是在DAN的帮助下正确工作的最终代码
hold on
N=100;
Points = rand(N,2);
SortedX = sortrows(Points,1);
NewVertices = SortedX;
plot(SortedX(:,1),SortedX(:,2),'*');
while length(NewVertices)>=3
X=NewVertices(:,1);
Y=NewVertices(:,2);
K = convhull(X,Y);
plot(X(K),Y(K),'r-');
for i=1:length(K)-1
NewVertices(K(i),1)=0;
NewVertices(K(i),2)=0;
end
NewVertices = NewVertices(any(NewVertices,2),:);
end