【发布时间】:2013-11-07 21:50:37
【问题描述】:
我正在尝试优化我的代码的性能(例如速度)。我是矢量化的新手,并尝试自己矢量化,但没有成功(也尝试 bxsfun、parfor、某种矢量化等)。谁能帮我优化这段代码,以及如何做到这一点的简短描述?
% for simplify, create dummy data
Z = rand(250,1)
z1 = rand(100,100)
z2 = rand(100,100)
%update missing param on the last updated, thanks @Bas Swinckels and @Daniel R
j = 2;
n = length(Z);
h = 0.4;
tic
[K1, K2] = size(z1);
result = zeros(K1,K2);
for l = 1 : K1
for m = 1: K2
result(l,m) = sum(K_h(h, z1(l,m), Z(j+1:n)).*K_h(h, z2(l,m), Z(1:n-j)));
end
end
result = result ./ (n-j);
toc
K_h.m 函数是边界核,定义为(x 是标量,y 可以是向量)
function res = K_h(h, x,y)
res = 0;
if ( x >= 0 & x < h)
denominator = integral(@kernelFunc,-x./h,1);
res = 1./h.*kernelFunc((x-y)/h)/denominator;
elseif (x>=h & x <= 1-h)
res = 1./h*kernelFunc((x-y)/h);
elseif (x > 1 - h & x <= 1)
denominator = integral(@kernelFunc,-1,(1-x)./h);
res = 1./h.*kernelFunc((x-y)/h)/denominator;
else
fprintf('x is out of [0,1]');
return;
end
end
获取结果需要很长时间:\经过的时间为 13.616413 秒。
谢谢。欢迎任何cmets。 P/S: 对不起我的英语不好
【问题讨论】:
-
j和n是什么?常量? -
和
h?请使用clear all,然后尝试执行您的代码,您会注意到任何缺少的初始化。 -
感谢@BasSwinckels。我刚刚更新了。对不起我的错误
-
感谢@DanielR。我刚刚更新了
标签: matlab optimization vectorization