3
$\begingroup$

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 ?

$\endgroup$
4
  • 1
    $\begingroup$ Use replacement Rules, maybe: Inner[#1.J.#2 &, x, y] /. Dot[x_, y_, z1_] + Dot[x_, y_, z2_] :> Dot[x, y, z1 + z2] $\endgroup$
    – march
    Commented Jun 30, 2016 at 18:43
  • $\begingroup$ Can you give a Mathematica expression for the result you would like? $\endgroup$
    – mikado
    Commented Jul 1, 2016 at 18:51
  • $\begingroup$ @march Thanks for your answer, but how could I also make the left side combinable ? $\endgroup$
    – kevin
    Commented Jul 1, 2016 at 19:14
  • $\begingroup$ @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)$. $\endgroup$
    – kevin
    Commented Jul 1, 2016 at 19:16

1 Answer 1

1
$\begingroup$

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 *)
$\endgroup$
2
  • $\begingroup$ Thanks. Could you give me a link to explain what this symbol :> means ? $\endgroup$
    – kevin
    Commented Jul 1, 2016 at 19:53
  • $\begingroup$ 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. $\endgroup$
    – march
    Commented Jul 1, 2016 at 19:54

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.