4
$\begingroup$

Is there a way to dot two vectors that are included in a list? Let's say I have two lists that contain a couple of vectors

list1 = {{1,2,3},{2,4,6},{1,5,7}}
list2 = {{4,1,9},{1,4,3},{2,8,3}}

and I would like to take the dot product between each of the vectors and give out the result in a new list. This function function[list1,list2] would then do something like

{{1,2,3}.{4,1,9},{2,4,6}.{1,4,3},{1,5,7}.{2,8,3}}
(*
{33, 36, 63}
*)
$\endgroup$
2
  • 4
    $\begingroup$ MapThread[Dot, {list1, list2}, 1] $\endgroup$
    – C. E.
    Aug 23, 2019 at 18:01
  • $\begingroup$ Or Dot @@@ Transpose[{list1, list2}]. $\endgroup$
    – march
    Aug 28, 2019 at 16:24

1 Answer 1

8
$\begingroup$

As mentioned in the comments, the obvious approach is to use MapThread. However, if you have large lists of vectors, a faster approach is to rely on listability:

a = RandomReal[1, {10^5, 100}];
b = RandomReal[1, {10^5, 100}];

r1 = Total[a b, {2}]; //RepeatedTiming
r2 = MapThread[Dot,{a, b}]; //RepeatedTiming

r1 == r2

{0.021, Null}

{0.187, Null}

True

So, about an order of magnitude faster. If you want an even faster option, you might consider the internal, undocumented function NDSolve`FEM`MapThreadDot:

r3 = NDSolve`FEM`MapThreadDot[a, b]; //AbsoluteTiming

r1 == r3

{0.012493, Null}

True

The internal function is about 2 times faster.

$\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.