【问题标题】:Increase Matlab code speed提高 Matlab 代码速度
【发布时间】:2015-11-11 02:16:04
【问题描述】:

有没有人能帮我提高下面代码的速度,太长了。问候。

limits(1) = 3.2;    
limits(3) = 3.6;
x = ones(426,1);   
y = ones(426,1);
BandWidth = 20;
height = 586;
width = 896;

dmap = zeros(height, width);
parfor  jj = 0 : width - 1
    myTemp = zeros(1, height);
    xi = limits(1) + jj;
    for ii = 0: height - 1
        yi = limits(3) + ii;
        myTemp(ii+1) = sum( exp(-((x - xi).^2 + (y - yi).^2)/(2*BandWidth^2)) );
    end
    dmap(:,jj+1) = myTemp';
end
dmap = (1/(sqrt(2*pi)*BandWidth))*dmap;

期待听到一些提示。

【问题讨论】:

标签: performance matlab for-loop parfor


【解决方案1】:

减小尺寸。例如:

身高 = 128;宽度 = 192

准确性将相似,但执行时间会更少。

【讨论】:

  • 我可以试试。谢谢塔里克
【解决方案2】:

这个使用矢量化实际上可以很好地加速(注意使用bsxfun)。我使用exp(A+B)=exp(A)*exp(B) 分别为xy 计算exp(-(x-xi)^2/(2*BandWidth^2)) 的事实,然后通过普通矩阵乘法处理求和,这是另一个不错的技巧。您的原始代码在我的计算机上运行了约 5.5 秒,此代码需要约 0.07 秒。在 3.23.6 附近,xy 的准确度确实会有所下降,但差异仍然低于 1e-14。我的直觉是,这是由于exp(A+B)exp(A)*exp(B) 之间的舍入误差造成的。

limits(1) = 3.2;    
limits(3) = 3.6;
x = ones(426,1);   
y = ones(426,1);
BandWidth = 20;
height = 586;
width = 896;
xi=limits(1)+(0:width-1);
yi=limits(3)+(0:height-1);
X=exp(-bsxfun(@minus,x,xi).^2/(2*BandWidth^2));
Y=exp(-bsxfun(@minus,y,yi).^2/(2*BandWidth^2));
dmap=Y.'*X/(sqrt(2*pi)*BandWidth);

【讨论】:

  • 好点使用 exp() 属性。够了!非常感谢
猜你喜欢
  • 1970-01-01
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多