3

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.

kglr
  • 394,356
  • 18
  • 477
  • 896
An old man in the sea.
  • 2,527
  • 1
  • 18
  • 26

4 Answers4

7

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.

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
1
x = {{a, b}, {c, d}} ;
mat = RandomInteger[{1, 5}, {2, 2}];


Inner[Times, mat, #] & /@ x // Transpose
Karsten7
  • 27,448
  • 5
  • 73
  • 134
Alucard
  • 2,639
  • 13
  • 22
0

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}}]*)
E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
-1

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.

Karsten7
  • 27,448
  • 5
  • 73
  • 134
John
  • 19
  • 2
  • n cannot be arbitrary as it would prevent matrix multiplication if the dimensions are not proper. – Syed Dec 10 '22 at 11:30
  • you misinterpreted my answer. n is the number of vectors in the list . – John Dec 12 '22 at 04:57