I have a list of vectors vecs = {vec1, vec2, ..., vecN} where veci is a list with length $N$.

Now I have a matrix $N\times N$ called mat.

I would like to efficiently get all the numbers veci.mat.veci for $i=1$ to $N$ in a list. How do I do it?

  • 3
    $\begingroup$ Perhaps, MapThread[Dot,{vecs.mat,vecs}]? (untested). $\endgroup$ – Leonid Shifrin Nov 11 '13 at 21:26
  • $\begingroup$ @LeonidShifrin Is your matrix multiplication engine broken? $\endgroup$ – Dr. belisarius Nov 11 '13 at 21:31
  • $\begingroup$ @belisarius Let's say it is just busy :). Actually, even just a simplest sample input with expected output would make this question way more attractive, and I guess not just for me. $\endgroup$ – Leonid Shifrin Nov 11 '13 at 21:33
  • $\begingroup$ @LeonidShifrin It works. Thanks! $\endgroup$ – lagoa Nov 11 '13 at 21:50
  • $\begingroup$ All right, I will then post this as an answer, to not keep this among the unanswered questions. $\endgroup$ – Leonid Shifrin Nov 11 '13 at 22:12

This is one way:


Here's another way:

Total[vecs.mat * vecs, {2}]

If the vectors happen to come naturally as the columns of vecs,
rather than its rows, then this will get what you want:

Total[vecs * mat.vecs]

One way to calculate is to leave everything in matrix form

v = RandomReal[{-1, 1}, {m=5, 10}];
mat = RandomReal[{-1, 1}, {10, 10}]; 

Since we're looking for fast ways, this seems faster:

v = RandomReal[{-1, 1}, {m=1000, 10}];
mat = RandomReal[{-1, 1}, {10, 10}];
v[[#]].mat.v[[#]] & /@ Range[m]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.