矢量化嵌套循环

时间:2016-01-26 12:52:50

标签: performance matlab vectorization

for k=1:n
    for m=1:n_
        K_anv(k,m,:)=exp(-(x(k,:)-z(m,:)).^2./(2*l'.^2))-A(k,:).*A_(m,:)./B;
    end
end

K_anv是表示内核的3D矩阵,其中k是数据的数量,m是估算点的数量。 xzn x Dn_ x D矩阵(lD x 1向量)。

在这种情况下,我可以消除循环吗?

1 个答案:

答案 0 :(得分:2)

使用bsxfun -

零碎的矢量化

%// Vectorize "-(x(k,:)-z(m,:)).^2" & thus "exp(-(x(k,:)-z(m,:)).^2./(2*l'.^2))"
xz = -bsxfun(@minus,permute(x,[1 3 2]),permute(z,[3 1 2])).^2 %//'
parte1 = exp(bsxfun(@rdivide,xz,permute(2*l'.^2,[1 3 2])))    %//'

%// Vectorize "A(k,:).*A_(m,:)" & thus "A(k,:).*A_(m,:)./B"
AA_ = bsxfun(@times,permute(A,[1 3 2]),permute(A_,[3 1 2]))
parte2 = bsxfun(@rdivide,AA_,permute(B,[1 3 2]))

%// Finally subtract parte2 from parte1 to get K_anv equivalent
K_anv_out = parte1 - parte2;