How to make fast multi-dimensional vector matrix multiplication?

Ais a three-dimensional matrix N * N * L, xis a vector N * 1, on which I need to perform the following operation:

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

I hope to use the most efficient vector method instead of a loop for. Please give me some advice?

+4
source share
2 answers

C bsxfun-

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

C matrix-multiplication-fun-

reshape(x*x.',1,[])*reshape(A,[],L)
+5
source
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,:));

Thanks @AndrasDeak, although you missed the last call squeeze.

+2
source

Source: https://habr.com/ru/post/1614062/


All Articles