使用cellfun在Matlab中加速while循环

时间:2017-06-07 00:57:19

标签: matlab while-loop

我在Matlab中有以下代码。

pc = [0.0195    0.2356    0.6280
    0.0229    0.2356    0.6280
    0.0393    0.2318    0.6180
    0.0196    0.2350    0.6310
    0.0212    0.2343    0.6290
    0.0230    0.2350    0.6310
    0.0245    0.2332    0.6260
    0.0378    0.2313    0.6210
    0.0408    0.2294    0.6160
    0.0426    0.2302    0.6180];

x = pc(:,1);
y = pc(:,2);
z = pc(:,3);

dt = delaunayTriangulation(pc);
dtTri = [dt(:,[1,2,3]);dt(:,[2,3,4]);dt(:,[1,2,4]);dt(:,[1,3,4])];
dtTri = unique(sort(dtTri,2),'rows');

i = 1;
lim = .005;

while (i<=size(dtTri,1))
    d12 = sqrt(abs(x(dtTri(i,1))-x(dtTri(i,2)))^2+...
        abs(y(dtTri(i,1))-y(dtTri(i,2)))^2+...
        abs(z(dtTri(i,1))-z(dtTri(i,2)))^2);

    if (d12>lim)
        dtTri(i,:)=[];
        continue;
    end
    i = i+1;
end

Matlab有没有办法减少上述代码(while循环)的运行时间,使用像cellfun之类的东西?因为我的pc大小非常大,运行代码需要很长时间。谢谢。

1 个答案:

答案 0 :(得分:1)

如果我理解了这个问题,您可以删除整个while并将其替换为以下代码:

 d12 = sqrt((x(dtTri(:,1))-x(dtTri(:,2))).^2 + ...
 (y(dtTri(:,1))-y(dtTri(:,2))).^2 + ...
 (z(dtTri(:,1))-z(dtTri(:,2))).^2);
 foundLimit = find(d12 <= lim);
 newDtTri = dtTri(foundLimit,:);