Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>OK, writing rules that play nice with the attributes of <code>NonCommutativeMultiply</code> is sometimes a hassle. Here's an alternate method which introduces a helper <code>NCM</code> that does not have the rules and attributes of <code>NonCommutativeMultiply</code> associated with it.</p> <p>The following code also incorporates the last couple of your questions. <a href="https://stackoverflow.com/q/4988323/421225">(1)</a> <a href="https://stackoverflow.com/q/5001368/421225">(2)</a></p> <pre><code>Unprotect[NonCommutativeMultiply]; Clear[NonCommutativeMultiply] (* Factor out numerics -- could generalize to some ScalarQ *) nc:NonCommutativeMultiply[a__]/;MemberQ[{a},_?NumericQ]:=NCMFactorNumericQ[NCM[a]]/.NCM-&gt;NonCommutativeMultiply (* Simplify Powers *) b___**a_^n_.**a_^m_.**c___:=NCM[b,a^(n+m),c]/.NCM-&gt;NonCommutativeMultiply (* Expand Brackets *) nc:NonCommutativeMultiply[a___,b_Plus,c___]:=Distribute[NCM[a,b,c]]/.NCM-&gt;NonCommutativeMultiply (* Sort Subscripts *) c___**Subscript[a_, i_]**Subscript[b_, j_]**d___/;i&gt;j:=c**Subscript[b, j]**Subscript[a, i]**d Protect[NonCommutativeMultiply]; Unprotect[NCM]; Clear[NCM] NCMFactorNumericQ[nc_NCM]:=With[{pos=Position[nc,_?NumericQ,1]},Times@@Extract[nc,pos] Delete[nc,pos]] NCM[a_]:=a NCM[]:=1 Protect[NCM]; </code></pre> <p>Note that <code>NCMFactorNumericQ</code> is fast because it works in a single pass, but the rule associated with it <code>nc:NonCommutativeMultiply[a__]/;MemberQ[{a},_?NumericQ]</code> is slow, because the Flat attribute means that it does a stupid number of checks using <code>NumericQ</code>. If you really want more speed and have large expressions, then you should just manually apply the <code>Sort</code> and <code>Factor</code> routines, so that Mathematica does less pattern checks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload