1
$\begingroup$

I found the Wolfram example for ExpandNCM but I want a more human-readable output form. I want to evaluate ExpandNCM, for example with ExpandNCM[(a**b+c**d)**(e**f+g**h)] = a**b**e**f + ..., but then I need to keep the order of all expression parts (abef+...) without those annoying **. It isn't allowed to change the position of abef to eabf or something like that. I tried to ExpandNCM[...]/. NonCommutativeMultiply:>Times but this doesn't work unfortunately.

$\endgroup$
3
$\begingroup$
expandNCM[(h : NonCommutativeMultiply)[a___, b_Plus, c___]] := 
 Distribute[h[a, b, c], Plus, h, Plus, ExpandNCM[h[##]] &]

expandNCM[(h : NonCommutativeMultiply)[a___, b_Times, c___]] := 
 Most[b] ExpandNCM[h[a, Last[b], c]]

expandNCM[a_] := ExpandAll[a]

To eliminate ** operators:

compressNCM[expr_] := expr /. NonCommutativeMultiply[x__] :>
   StringJoin@(ToString /@ {x})

To return to original notation:

toNCM[expr_] := 
 expr /. str_String :> 
   NonCommutativeMultiply @@ (ToExpression /@ Characters[str])

encm = expandNCM[(a ** b + c ** d) ** (e ** f + g ** h)]

a ** b ** e ** f + a ** b ** g ** h + c ** d ** e ** f + c ** d ** g ** h

% // compressNCM

abef + abgh + cdef + cdgh

However, the above expression cannot be operated on further without converting back to the normal form with toNCM. As written, the conversion back only works for single character factors.

encm == % // toNCM

True

$\endgroup$
  • $\begingroup$ Great help!!!!! $\endgroup$ – Saesun Kim Oct 25 '15 at 4:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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