Need to optimize this matlab code..vectorization will help or not?
Possible Duplicate:
Optimization a recurring matlab code
向量化是优化这段代码的好选择吗?什么标准决定我们是否对代码进行矢量化?还能做什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 |
请做一些研究,谷歌上有用的点击量简直是压倒性的:
等。
话虽如此:您的代码表明您只想确定一个点是否位于多边形内。在那种情况下,何必麻烦,因为
现在,如果您想对大量点执行此操作,但多边形中的顶点不多(或相反),您最好将点数组传递给函数: 因为这使 Matlab 能够在两个循环中使用 JIT。一个简单的测试:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
2
3
4
5
6
7
8
结果:
1 | Elapsed time is 0.324801 seconds. |
现在,如果您想对大量点进行测试,在多边形中有大量顶点,您最好将所有这些都转换为 C 并编写一个 mex 文件。毕竟这是一个相当繁重的算法,当你对它也提出了很高的要求时,你将不得不切换你的工具集。