I'm making a small hacky notebook and want to avoid using external libraries. In my notebook, I'd like multiplication to be non-commutative only for a particular family of expressions whilst still using Times
(not NonCommutativeMultiply
).
The expressions have the form Subscript[symb_Symbol, _Integer]
where symb
is a member of (e.g.) [A
, B
, C
]. There are few symbols, so I'm happy to hardcode rules.
I'd like, for example
Times[Subscript[B, 2], Subscript[A, 1]]
to be unchanged, rather than have the order of the terms automatically commuted.
I've seen this solution where Times
of a particular Head matrix
is made non-commutative, and I've seen how NCAlgebra does it, but I can't manage to adapt either for my purposes.
I'd actually prefer to substitute Times
for Dot
when it contains one of these expressions. I know I can define a function with the HoldAll
attribute and replace Times
to Dot
before Mathematica commutes the expression, but I'd like this behaviour everywhere, not just in the function argument.
In affect, this would give behaviour like (for special symbols A
, B
, C
):
$B_2 A_2 + G F E$ would evaluate to $B_2 . A_2 + E F G$
Is this possible without immense complication?
ClearAttributes[Times, Orderless]; Times[x___, Subscript[a_, n_], y___] ^:= Dot[x, Subscript[a, n], y]
. It will useDot
instead ofTimes
every time aSubscript
appears insideTimes
. It's necessary to clearOrderless
attribute in order to preserve the order of arguments though. $\endgroup$Times
? Mathematica tends to be unpredictable sometimes. Based on past experience, I would not dare mess with such a fundamental built-in asTimes
. $\endgroup$