I need a noncommutative multiplication that is

  1. Associative
  2. Distributive
  3. $A**0=0$, $A**1=A$
  4. Agrees with the commutative multiplication ($A**(k B)=(k A)**B=k (A**B)$)

I have found a code

     (*Factor out numerics -- could generalize to some ScalarQ*)
nc : NonCommutativeMultiply[a__] /; MemberQ[{a}, _?NumericQ] := 
  NCMFactorNumericQ[NCM[a]] /. NCM -> NonCommutativeMultiply
     (*Simplify Powers*)
b___ ** a_^n_. ** a_^m_. ** c___ := 
  NCM[b, a^(n + m), c] /. NCM -> NonCommutativeMultiply
     (*Expand Brackets*)
nc : NonCommutativeMultiply[a___, b_Plus, c___] := 
  Distribute[NCM[a, b, c]] /. NCM -> NonCommutativeMultiply
     (*Sort Subscripts*)
c___ ** Subscript[a_, i_] **Subscript[b_, j_] ** d___ /; i > j := 
  c ** Subscript[b, j] ** Subscript[a, i] ** d

NCMFactorNumericQ[nc_NCM] := 
  With[{pos = Position[nc, _?NumericQ, 1]}, Times \@@ Extract[nc, pos] Delete[nc, pos]]
NCM[a_] := a
NCM[] := 1

Here 1, 2, 3 are satisfied and 4 is not. Could you please help me to modify it.

  • $\begingroup$ If you want it to agree with ordinary multiplication, do Unprotect[NonCommutativeMultiply]; NonCommutativeMultiply[x___]:=Times[x] (you probably also need to set its attributes to those of Times). If you want it to have a notion of scalars that get pulled out, that's a very different matter. So you really need to spell out more carefully what it is you want, if in fact it is not to make NonCommutativeMultiply into Times. $\endgroup$ Mar 17, 2014 at 14:58

1 Answer 1


Try NCAlgebra. After setting some symbols to be commutative or noncommutative:

<< NC`
<< NCAlgebra`
SetNonCommutative[A, B]

the expressions

A ** (k B)
(k A) ** B
k A ** B

all evaluate to k A ** B.

  • $\begingroup$ Thanks but I need the forth condition to hold for any integer $k$ $\endgroup$
    – 8k14
    Apr 21, 2017 at 5:16
  • $\begingroup$ Integers and other numeric symbols will be treated as commutative by default. $\endgroup$ Apr 21, 2017 at 14:20
  • $\begingroup$ Great. Thanks a lot. $\endgroup$
    – 8k14
    Apr 24, 2017 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.