优化重复的matlab代码

时间:2012-10-15 12:23:00

标签: performance matlab optimization if-statement

我正在优化一个模型,该模型获取一些天气数据,然后将云转换为多边形,以便可以进一步利用它们。
代码正在运行,但其种类很慢。通过运行探查器,我发现以下行被称为106360430次,需要大约50秒才能处理。
有没有办法让这些线条更有效率?

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

3 个答案:

答案 0 :(得分:2)

inPolygon测试是一项繁重的功能,可能最好在mex文件中完成。以下是您可以查看的一些FEX贡献:inpoly-mex-fileFast Inpolygon in MEXFast InPolygon detection MEXHere是一个原生的matlab代码,比matlab inpoly更快。

答案 1 :(得分:1)

将代码矢量化(使用矩阵而不是使用循环),如下所示:

function [oddNodes] = pointInPolygon (point,thePolygon)

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

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

% this part has been vectorized:

thePolygon2=circshift(thePolygon,1);
t1=(thePolygon(:,2)<y & thePolygon2(:,2)>=y | thePolygon2(:,2)<y & thePolygon(:,2)>=y);
t2=(thePolygon(:,1)+(y-thePolygon(:,2))/(thePolygon2(:,2)-thePolygon(:,2))*(thePolygon2(:,1)-thePolygon(:,1))<x);

oddNodes=mod(sum(t1&t2),2);

答案 2 :(得分:0)

我没有测试它的速度,但一般的方法是: 尝试对代码进行矢量化,而不是运行相同的行106360430次。 因此,尝试像这样塑造它:

output = pointMatrixInPolygon (pointMatrix,thePolygon)

然后尝试避免函数内部的循环,你应该在那里。实际上,您可以将矩阵输入到常规的多边形函数中。