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
是估算点的数量。 x
和z
是n x D
和n_ x D
矩阵(l
是D x 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;