我正在尝试优化我的代码的性能(例如速度)。我是矢量化的新手,并尝试自己进行矢量化,但没有成功(也尝试 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
需要很长时间才能得到结果: \Elapsed time 为 13.616413 秒。
谢谢你。欢迎任何意见。P/S: 对不起我的英语不好