4
$\begingroup$

I have two 2x2 matrices, which elements are lists (so overall structure can be complicated). I need to perform matrix multiplication of these 2x2 matrices as if the elements didn't have its inner structure. But Mathematica's Dot[A, B] considers my matrices higher-dimentional and gives wrong result.

Then I introduced a function which literally perfoms 2x2 multiplication like this:

TwoMatrixProduct[a_, b_] := {
  {a[[1, 1]] b[[1, 1]] + a[[1, 2]] b[[2, 1]], 
   a[[1, 1]] b[[1, 2]] + a[[1, 2]] b[[2, 2]]},
  {a[[2, 1]] b[[1, 1]] + a[[2, 2]] b[[2, 1]], 
   a[[2, 1]] b[[1, 2]] + a[[2, 2]] b[[2, 2]]}}

and everything works fine, e.g.:

a = {a1, a2};
b = {b1, b2};
c = {c1, c2};
d = {d1, d2};
matrix2x2 = {{a,b},{c,d}}
TwoMatrixProduct[matrix2x2, matrix2x2]

(* {{{a1^2 + b1 c1, a2^2 + b2 c2}, 
     {a1 b1 + b1 d1, a2 b2 + b2 d2}}, 
    {{a1 c1 + c1 d1, a2 c2 + c2 d2}, 
     {b1 c1 + d1^2, b2 c2 + d2^2}}}  *)

Is there a better solution without manual typing of two matrices product?

$\endgroup$
0

1 Answer 1

5
$\begingroup$
matrix2x2
(* {{{a1, a2}, {b1, b2}}, {{c1, c2}, {d1, d2}}} *)
Map[Hold, matrix2x2, {2}]
(* {{Hold[{a1, a2}], Hold[{b1, b2}]}, {Hold[{c1, c2}], Hold[{d1, d2}]}} *)

And so:

ReleaseHold[Map[Hold, matrix2x2, {2}].Map[Hold, matrix2x2, {2}]]
(* {{{a1^2 + b1 c1, a2^2 + b2 c2},
     {a1 b1 + b1 d1, a2 b2 + b2 d2}},
    {{a1 c1 + c1 d1, a2 c2 + c2 d2},
     {b1 c1 + d1^2, b2 c2 + d2^2}}} *)
$\endgroup$
1
  • $\begingroup$ very nice! thanks! $\endgroup$
    – funnyp0ny
    Commented Nov 11, 2014 at 10:53

Your Answer

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

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