Expand and Simplify do not work for NonCommutativeMultiply then how do we expand an expression like
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.Sign up to join this community
There is more than one way to do this in Mathematica. I prefer a simple approach as in the following code:
Unprotect[NonCommutativeMultiply]; a___ ** (b_ + c_) ** d___ := a ** b ** d + a ** c ** d; a___ ** (n_?NumericQ b_) ** c___ := n (a ** b ** c); a__ ** (n_?NumericQ) := n a; (n_?NumericQ) ** a__ := n a;
which should do what you expect. For exmaple:
(a + b) ** (a - b) == a ** a - a ** b + b ** a - b ** b
True. The last line of code allows the code
x ** 0 == 0 == 0 ** x && x ** -1 == -x == -1 ** x
to evaluate to
True. Note that this solution automatically expands expressions containing
**. If you don't want this to happen, then an alternative way to do this is to change the
:> instead and make them into a list of rules.
Up to the documentation to
**, "Expand and Simplify do not operate on expressions with NonCommutativeMultiply". According to this documentation, the following works.
ClearAll["Global`*"];ExpandNCM[(h : NonCommutativeMultiply)[a___, b_Plus, c___]] := Distribute[h[a, b, c], Plus, h, Plus, ExpandNCM[h[##]] &]; ExpandNCM[a_] := ExpandAll[a]; ExpandNCM[(a + b) ** (c + d)]