# Multiplying a list a vectors by the same matrix

I have a list of 2 vectors: x={{a,b},{x,y}}, and a matrix 2 by 2 A.

I want the result to be {A.{a,b},A.{x,y}}.

I thought we could do A.x, but it doesn't work. Also, I've tried something with apply or applythread but no sucess...

Any help would be appreciated.

• How about Transpose[A . Transpose[x]] Aug 4, 2017 at 23:47
• Change x={{a,b},{x,y}} to xx={{a,b},{x,y}} and A.#&/@xx works.
– kglr
Aug 4, 2017 at 23:50
• A more general perspective can be seen comparing a suggestion by @CarlWoll with this answer Add a vector to a list of vectors. One can just change Dot or Plus to any two-argument action. Aug 5, 2017 at 0:02
• @Artes Thanks for the extra info which is very useful right now! Aug 5, 2017 at 7:49

If you are working with large matrices, then matrix dot products are almost certainly the best approach if you are interested in speed. For example, suppose you have a 200 x 200 matrix, and 100 vectors:

A = RandomReal[1, {200, 200}];
v = RandomReal[1, {100, 200}];


Let's compare a few methods:

r1 = Transpose[A . Transpose[v]]; //AbsoluteTiming
r2 = A . #& /@ v; //AbsoluteTiming
r3 = Inner[Times, A, #]& /@ v; //AbsoluteTiming

r1 == r2 == r3


{0.000335, Null}

{0.007227, Null}

{29.0056, Null}

True

Clearly, using Inner instead of Dot for large matrices is much slower. Now, for even larger matrices:

A = RandomReal[1, {2000, 2000}];
v = RandomReal[1, {100, 2000}];

r1 = Transpose[A . Transpose[v]]; //AbsoluteTiming
r2 = A . #& /@ v; //AbsoluteTiming

r1 == r2


{0.007186, Null}

{0.356008, Null}

True

Matrix multiplication using Dot is heavily optimized.

• Thanks Carl! Much appreciated! Aug 5, 2017 at 7:43
x = {{a, b}, {c, d}} ;
mat = RandomInteger[{1, 5}, {2, 2}];

Inner[Times, mat, #] & /@ x // Transpose

• Thanks for the answer. ;) Aug 5, 2017 at 7:43

Using Fold:

A = Array[Subscript[b, ##] &, {2, 2}];
X = {{a, b}, {x, y}};
Fold[Dot[#1, Transpose@#2] &, X, {A}] === {A . {a, b}, A . {x, y}}
(*True*)


To prevent matrix multiplication if the dimensions are not proper (as pointed out Syed), you can build your own dot product as follows:

MyDot[A_?MatrixQ, vecs_?MatrixQ] /; SameQ[Last@Dimensions[A],
Mean@(Length[#] & /@ vecs)] :=
Fold[Dot[#1, Transpose@#2] &, vecs, {A}]


Test 1:

MyDot[A, X] === {A . {a, b}, A . {x, y}}
(*True*)


Test 2:

X2 = {{a, b, c}, {x, y}};
MyDot[A, X2]
(*MyDot[{{Subscript[b, 1, 1], Subscript[b, 1, 2]}, {Subscript[b, 2, 1], Subscript[b, 2, 2]}}, {{a, b, c}, {x, y}}]*)


If m is a 2X2 matrix and v is a list of 2D vectors of length n Table[m.v[[i]],{i,1,n}] is a list of the new vectors.

• n cannot be arbitrary as it would prevent matrix multiplication if the dimensions are not proper.
– Syed
Dec 10, 2022 at 11:30
• you misinterpreted my answer. n is the number of vectors in the list .
– John
Dec 12, 2022 at 4:57