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?
With bsxfun
-
sum(reshape(bsxfun(@times,x,bsxfun(@times,A,x.')),[],L),1)
With matrix-multiplication-fun
-
reshape(x*x.',1,[])*reshape(A,[],L)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With