2
$\begingroup$

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?

$\endgroup$
5
  • 3
    $\begingroup$ Perhaps, MapThread[Dot,{vecs.mat,vecs}]? (untested). $\endgroup$ Nov 11, 2013 at 21:26
  • $\begingroup$ @LeonidShifrin Is your matrix multiplication engine broken? $\endgroup$ Nov 11, 2013 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$ Nov 11, 2013 at 21:33
  • $\begingroup$ @LeonidShifrin It works. Thanks! $\endgroup$
    – lagoa
    Nov 11, 2013 at 21:50
  • $\begingroup$ All right, I will then post this as an answer, to not keep this among the unanswered questions. $\endgroup$ Nov 11, 2013 at 22:12

3 Answers 3

3
$\begingroup$

This is one way:

MapThread[Dot,{vecs.mat,vecs}]
$\endgroup$
2
$\begingroup$

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]
$\endgroup$
1
$\begingroup$

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]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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