What you want to do is tricky. You are mixing two things:
- You want noncommutative products based on upvalues of the symbols involved;
- You want to be able to replace the symbols by matrices.
Both can be achieved with NCAlgebra
. The latest distribution is available from:
https://github.com/NCAlgebra/NC
The example from one of your comments in NCAlgebra
would look like this:
<< NC`
<< NCAlgebra`
f[a_, b_] := a + b - b^2 - b ** a
Because a
and b
are noncommutative by default,
f[a, b]
results in
a + b - b ** a - b ** b
whereas
f[A, b]
results in
A + b - A b - b ** b
The second **
gets downgraded to a regular Times
because A
is commutative. This accomplishes task 1.
The task 2. is more subtle. If you want to substitute a
and b
for matrices you can use NCMatrixReplaceAll
. For example:
AA = {{1, 2}, {3, 4}}
BB = {{-1, 0}, {1, 2}}
and
NCMatrixReplaceAll[f[a, b], {a -> AA, b -> BB}]
would result in
{{0, 4}, {-4, -8}}
which is what you get out of AA + BB - BB.BB - BB.AA
, as you might expect. Note that the regular RepleceAll
(\.
) will fail because of the way Mathematica mixes Lists with other expressions when Plus
is involved. This is why f[AA,BB]
would also fail.
NCMatrixReplaceAll
also works with matrices that have noncommutative entries. For example:
AA = {{1, d}, {c, 4}}
BB = {{a, b}, {1, d}}
NCMatrixReplaceAll[f[a, b], {a -> AA, b -> BB}]
returns
{{1 - b - a ** a - b ** c, -3 b + d - a ** b - a ** d - b ** d},
{-a + c - d - d ** c, 4 - b - 4 d - d ** d}}
which is what you would obtain from AA + BB - NCDot[BB, BB] - NCDot[BB, AA]
.