如何进行快速多维矩阵向量乘法?

时间:2015-11-01 20:28:43

标签: performance matlab matrix vectorization matrix-multiplication

A是3D N * N * L矩阵,x是N * 1向量,我需要在其上执行以下操作:

for i=1:L
    res(i)=x'*squeeze(A(:,:,i))*x
end

我希望使用最有效的矢量化方法而不是for循环。请有人给我一些建议吗?

2 个答案:

答案 0 :(得分:5)

使用bsxfun -

sum(reshape(bsxfun(@times,x,bsxfun(@times,A,x.')),[],L),1)

使用matrix-multiplication-fun -

reshape(x*x.',1,[])*reshape(A,[],L)

答案 1 :(得分:2)

N=10;L=5;
A = rand(N,N,L);x=rand(N,1);
C = sum(sum(bsxfun(@times,permute(bsxfun(@times,permute(A,[3 1 2]),reshape(x,[1 1 N])),[1 3 2]),reshape(x,[1 1 N])),2),2);
C = squeeze(C(:,1,:));

感谢@AndrasDeak,尽管您确实错过了上次squeeze来电。

相关问题