优化重复的matlab代码 [英] Optimization a recurring matlab code

查看:392
本文介绍了优化重复的matlab代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在优化一个模型,该模型获取一些天气数据,然后将云转换为多边形,以便可以进一步利用它们。

代码正在运行,但它的种类很慢。通过运行探查器,我发现以下行被称为 106360430 次,需要大约50秒才能处理。

有没有办法让这些线条更有效率?

I'm optimizing a model which takes some weather data and then converts the clouds into polygons, so that they can be further utilized.
The code is working, but its kinds slow. By running the profiler I was able to found out the following lines are being called 106360430 times and takes about 50 secs to process.
Is there a way I can make these lines more efficient?

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


推荐答案

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

Vectorize your code (work on a matrix instead of using a loop) like this:

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);

这篇关于优化重复的matlab代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆