Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a fast multidimensional matrix vector multiplication?

A is a 3D N*N*L matrix, x is a N*1 vector, on which I need to do the following operation:

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

I hope to use most efficient vectorized method instead of a for loop. Please anyone give me some suggestions?

like image 833
J. Andrew Avatar asked Mar 14 '23 07:03

J. Andrew


2 Answers

With bsxfun -

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

With matrix-multiplication-fun -

reshape(x*x.',1,[])*reshape(A,[],L)
like image 104
Divakar Avatar answered Mar 16 '23 20:03

Divakar


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 to @AndrasDeak, though you did miss the last squeeze call.

like image 25
Adriaan Avatar answered Mar 16 '23 22:03

Adriaan