1
$\begingroup$

I want to symbolically replace occurences of matrix terms such as $zAB-zBA$ with $zC$, where $z$ is a number. This works as expected:

rule = q_.*(x_).(y_) - q_.*(y_).(x_) -> q*c;
z*a.b - z*b.a /. rule
(* Result: c z *)

The above also works if there is no z, yielding c as expected. However, it does not work with numeric coefficients:

2*a.b - 2*b.a /. rule
(* Result: 2 a.b - 2 b.a *)
(* Expected: 2 c *)

I tried changing the rule to q_Number*(x_).(y_) - q_Number*(y_).(x_) -> q*c, but it returns the same result.
I can use FactorTerms before applying the rules, but that will not work e.g. for the case 2*a.b - 2*b.a + 1.

How do I handle the case with numeric coefficients?

$\endgroup$
2
  • 1
    $\begingroup$ Suppress evaluation of patterns enclosing the left side in HoldPattern and use :> instead -> . Coefficients with different signs are difficult to handle for numbers becaus of different classes, integers, reals, rationals, complexes. I usually use conditonal rules HoldPattern[ p_.*(x_) . (y_) + q_.*(y_) . (x_)] :> p*c /; p + q == 0 $\endgroup$
    – Roland F
    Oct 26, 2023 at 22:36
  • $\begingroup$ This asnwers my question, thank you. BTW, it seems to produce the expected result even without HoldPattern: 2 a.b - 2 b.a //. p_.*(x_) . (y_) + q_.*(y_) . (x_) :> p*c /; p + q == 0 $\endgroup$
    – Yashman
    Oct 27, 2023 at 10:03

1 Answer 1

1
$\begingroup$

I'd suggest using a normal-ordering rule instead of trying to pattern-match a commutator directly.

With the commutator $\Gamma_{x,y}=x\cdot y-y\cdot x=-\Gamma_{y,x}$ we can replace $x\cdot y\to y\cdot x-\Gamma_{y,x}$ whenever $x\cdot y$ is not ordered,

rule = (x_) . (y_) /; !OrderedQ[{x, y}] -> y . x - Γ[y, x];

and thus end up only with ordered components and ordered commutators.

Try it out:

z*a.b - z*b.a /. rule // Expand
(*    z Γ[a, b]    *)

2*a.b - 2*b.a /. rule // Expand
(*    2 Γ[a, b]    *)

2*a.b - 3*b.a /. rule // Expand
(*    -a.b + 3 Γ[a, b]    *)

You can then substitute Γ[a, b] -> c if you like, of course.

$\endgroup$
1
  • $\begingroup$ Accepting this as a solution, although it might not be desirable to apply reordering to every term in the expression. Given z*a.b - z*b.a + c.a, I'd rather c.a be left as is. Perhaps in that respect pattern-matching is more appropriate, but it depends on what one is trying to achieve. $\endgroup$
    – Yashman
    Oct 29, 2023 at 9:48

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.