Efficient matrix multiplication

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?

• Perhaps, MapThread[Dot,{vecs.mat,vecs}]? (untested). – Leonid Shifrin Nov 11 '13 at 21:26
• @LeonidShifrin Is your matrix multiplication engine broken? – Dr. belisarius Nov 11 '13 at 21:31
• @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. – Leonid Shifrin Nov 11 '13 at 21:33
• @LeonidShifrin It works. Thanks! – lagoa Nov 11 '13 at 21:50
• All right, I will then post this as an answer, to not keep this among the unanswered questions. – 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}];
Diagonal[v.mat.Transpose[v]]

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]