# How to do abstract matrix operation?

In this simple example, I have 2 lists, each of which contains 3 matrices。 $J$ here is also a matrix with the same dimension. What I want is $aJc+bJ(b+c)$, but if I use dot product, the result is as follows,

x = {a, b, b}; y = {c, b, c};
Sum[x[[i]] .J. y[[i]], {i, 1, 3}] // FullSimplify
(* return is a.J.c + b.J.b + b.J.c *)


When I use multiplication, then Mathematica goes too far:

x = {a, b, b}; y = {c, b, c};
Sum[x[[i]] *J* y[[i]], {i, 1, 3}] // FullSimplify
(* return is (b^2 + (a + b) c) J*)


So how to get what I want ?

• Use replacement Rules, maybe: Inner[#1.J.#2 &, x, y] /. Dot[x_, y_, z1_] + Dot[x_, y_, z2_] :> Dot[x, y, z1 + z2] – march Jun 30 '16 at 18:43
• Can you give a Mathematica expression for the result you would like? – mikado Jul 1 '16 at 18:51
• @march Thanks for your answer, but how could I also make the left side combinable ? – kevin Jul 1 '16 at 19:14
• @mikado The structure is the multiplication of 3 matrix $\{a, J, b\}$. The middle matrix is always $J$, and I want the left and right matrices are combinable. I think it is tensor product and I want to combine the factors. For instance, $aJb+bJb=(a+b)Jb$, and $aJb+aJa=aJ(a+b)$. – kevin Jul 1 '16 at 19:16

We can surely generalize this (to include scalar multiples, for instance), but here's an implementation that factors the expression written in terms of Dots:

dotFactor[expr_] := expr //. {
Dot[x__, z1_] + Dot[x__, z2_] :> Dot[x, z1 + z2],
Dot[z1_, x__] + Dot[z2_, x__] :> Dot[z1 + z2, x],
Dot[1, x__] | Dot[x__, 1] :> Dot[x]
}


Then, using

x = {a, b, b};
y = {c, b, c};


we get

expr = Inner[#1.J.#2 &, x, y]
expr // dotFactor
(* a.J.c + b.J.b + b.J.c *)
(* a.J.c + b.J.(b + c) *)


Also,

x = {a, b, b, d, a};
y = {c, b, c, d, b};
expr = Inner[#1.J.#2 &, x, y]
expr // dotFactor
(* a.J.b + a.J.c + b.J.b + b.J.c + d.J.d *)
(* (a + b).J.(b + c) + d.J.d *)

• Thanks. Could you give me a link to explain what this symbol :> means ? – kevin Jul 1 '16 at 19:53
• For any symbol or built-in function, just highlight it and hit the F1 key, and it will bring up the documentation page for that symbol/function. (This is RuleDelayed. It is the delayed version of a replacement rule where the right-hand side is evaluated only when the rule is called. – march Jul 1 '16 at 19:54