0

我是新来的,这是我的第一篇文章。我想知道是否有办法从 100 个随机点计算所有可能的凸包。我创建了一个正确的代码,但它给了我一个convhull 的错误以及该部分下方的所有内容都无法计算..换句话说,我想知道是否有一种方法可以在 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);

提前致谢

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
4

2 回答 2

1

该错误相当具有表现力,您没有指定足够的点(即至少 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 个点上运行的原因。

于 2013-04-03T11:39:58.767 回答
1

非常感谢丹,

首先,我尝试仅更改您说的那一行,但由于我正在使用的重塑功能,它不再起作用了。然后我决定更改它们,并使它变得更简单,并且确实起作用了!

这是在 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
于 2013-04-04T12:21:21.220 回答