[英]Increase Matlab code speed
Is anyone able to help me increasing the speed of the code below, it is taking too long.有没有人能帮我提高下面代码的速度,它花费的时间太长了。 Regards.问候。
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;
Looking foward hearing some tips.期待听到一些提示。
Decrease the dimensions.减少尺寸。 eg:例如:
height = 128;高度 = 128; width = 192宽度 = 192
The accuracy will be similar but the performance time will be less.准确性将相似,但性能时间会更少。
This one actually speeds up quite quite nicely using vectorisation (note the use of bsxfun
).这个实际上使用矢量化可以很好地加速(注意使用bsxfun
)。 I used the fact that exp(A+B)=exp(A)*exp(B)
to compute exp(-(x-xi)^2/(2*BandWidth^2))
separately for x
and y
, and then the summation is handled by normal matrix multiplication, another nice trick.我使用exp(A+B)=exp(A)*exp(B)
为x
和y
分别计算exp(-(x-xi)^2/(2*BandWidth^2))
的事实,然后求和由普通矩阵乘法处理,这是另一个不错的技巧。 You original code ran in ~5.5 seconds on my computer, this code takes ~0.07 seconds.您的原始代码在我的计算机上运行约 5.5 秒,此代码需要约 0.07 秒。 You do lose a little accuracy for x
and y
near 3.2
and 3.6
, but the difference is still below 1e-14
. x
和y
在3.2
和3.6
附近确实失去了一点精度,但差异仍然低于1e-14
。 My hunch is that it's due to round-off error between exp(A+B)
and exp(A)*exp(B)
.我的直觉是,这是由于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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.