需要优化这个matlab代码。向量化有没有帮助?

时间:2012-10-18 15:00:16

标签: performance matlab optimization for-loop vectorization

  

可能重复:
  Optimization a recurring matlab code

矢量化是优化这段代码的好选择吗?什么标准决定了我们是否对代码进行了矢量化?还有什么可以做的?

function [oddNodes] = pointInPolygon (point,thePolygon)
% determine if a point is in the polygon (faster than matlab "inpolygon"
% command

 polyPoints=size(thePolygon,1);     %number of polygon points
 oddNodes = false;

j=polyPoints;
x=point(1); y=point(2);

for i=1:polyPoints
if (thePolygon(i,2)<y && thePolygon(j,2)>=y ||  thePolygon(j,2)<y && thePolygon(i,2)>=y)
    if (thePolygon(i,1)+(y-thePolygon(i,2))/(thePolygon(j,2)-thePolygon(i,2))*(thePolygon(j,1)-thePolygon(i,1))<x)
        oddNodes=~oddNodes;
    end
end
j=i; 
end

1 个答案:

答案 0 :(得分:2)

请做一些研究,谷歌上有用的点击数量实在太多了:

  1. http://www.softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm
  2. http://www.mathworks.com/matlabcentral/fileexchange/10391-fast-points-in-polygon-test
  3. Geo Fencing - point inside/outside polygon
  4. http://www.mathworks.com/matlabcentral/fileexchange/12744-distance-from-a-point-to-polygon
  5. 等。

    话虽如此:您的代码建议您只想确定单个点是否位于多边形内。在这种情况下,为什么要麻烦,因为inpolygon可以确定在一个百万个顶点多边形的5秒内。

    现在,如果你想为多个点(但多边形中没有那么多的顶点)(或者反过来)那样做,那么你最好通过一个点数组进入功能:

    function in = pointInPolygon(points, poly)
    
        nn = size(poly,1);
        in = false(nn,1);
    
        for ii = 1:size(points,2)
    
            x = points(ii,1);
            y = points(ii,2);
    
            yn = false;
            for jj = 1:size(poly,1)
    
                if (poly(jj,2)<y && poly(nn,2)>=y || ...
                    poly(nn,2)<y && poly(jj,2)>=y)
    
                    if (poly(jj,1)+(y-poly(jj,2))/(poly(nn,2)-poly(jj,2))*...
                       (poly(nn,1)-poly(jj,1))<x)
                        yn = ~yn;
                    end
    
                end
                nn = jj;
            end
    
            in(ii) = yn;
    
        end
    
    end
    

    因为这使得Matlab能够在两个循环中使用JIT。一个简单的测试:

    poly = rand(6e6,2);
    poly = [poly ; poly(1,:)];
    
    xy   = rand(1e3,2);
    
    tic         
        in = pointInPolygon(xy, poly);
    toc
    

    结果:

    Elapsed time is 0.324801 seconds.
    

    现在,如果您想对个点进行测试,并且在多边形中使用个顶点数,那么您的翻译效果会更好所有这些到C并写一个mex文件。毕竟这是一个相当繁重的算法,当你也对它提出了很高的要求时,你将不得不切换你的工具集。