2012-10-18 36 views
-1

可能重复:
Optimization a recurring matlab code需要优化这个matlab代码...向量化会有帮助吗?

是矢量优化这段代码一个很好的选择?无论我们是否将代码矢量化,什么标准决定?还有什么可以做的?

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 
+0

矢量化的好坏取决于你想要达到的目标。如果你想要速度,你应该在你的代码上运行profiler,然后开始削减永久占用的线路。 – Jonas

回答

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

话虽如此:您的代码建议您只想确定一个点是否位于多边形内。在那种情况下,为什么要麻烦呢,因为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文件。毕竟这是一个相当沉重的算法,当你对它也提出了很高的要求时,你必须切换你的工具集。