4

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?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
J. Andrew
  • 43
  • 4
  • I suggest being more specific: you don't need matrix-vector multiplication, but computing a quadratic form. But it's possible that it only makes a difference for me:) – Andras Deak -- Слава Україні Nov 01 '15 at 20:37
  • I can't try it right now, but you might be after something like `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)` – Andras Deak -- Слава Україні Nov 01 '15 at 20:44
  • @J.Andrew I have rolled your question back to its previous state. This is because you updated your question making both answers, including the one you accepted as "helpful" out of date. If you have a new question, please open a new question rather than expanding on this one. – Adriaan Nov 04 '15 at 20:56

2 Answers2

5

With bsxfun -

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

With matrix-multiplication-fun -

reshape(x*x.',1,[])*reshape(A,[],L)
Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358
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,:));

Thanks to @AndrasDeak, though you did miss the last squeeze call.

Adriaan
  • 17,741
  • 7
  • 42
  • 75