Re: Stop mathematica reordering expression during matrix

*To*: mathgroup at smc.vnet.net*Subject*: [mg109409] Re: Stop mathematica reordering expression during matrix*From*: Leonid Shifrin <lshifr at gmail.com>*Date*: Sun, 25 Apr 2010 06:26:30 -0400 (EDT)

Hi Robert, One way to do what you want would be to disable the Orderless attribute of Times temporarily during the evaluation of your code: In[54]:= Unprotect[Times]; ClearAttributes[Times,Orderless]; C2=C1.C1; result = Hold[Evaluate[C2]]; SetAttributes[Times,Orderless]; Protect[Times]; In[60]:= result Out[60]= Hold[{{x1 x2,0,x1 x3,0},{x3 x4,x2 x1,0,x3 x5},{x5 x6,x4 x1,x5 x7,0},{x7 x4,x6 x1,0,x7 x5}}] However, as soon as you switch the Orderless attribute on, your answer will take the ordered form as soon as you allow it to evaluate, so you have to wrap it in something like Hold to prevent this from happening - this is what I've done. To use this result, you have a couple of choices. You can disable Orderless attribute for Times for the entire computation that you want to carry out. Alternatively, you can carefully construct your functions to work with held (unevaluated) results like the one we got. One more option would be to do whatever you want with this result while blocking Times: Block[{Times}, do-something-with-result]. Finally, you can replace Times by some other head, say <times>, replacing it back to Times at the end (when you are ready to do that): In[61]:= (result/.Times->times)//ReleaseHold//MatrixForm Out[61]//MatrixForm= (times[x1,x2] 0 times[x1,x3] 0 times[x3,x4] times[x2,x1] 0 times[x3,x5] times[x5,x6] times[x4,x1] times[x5,x7] 0 times[x7,x4] times[x6,x1] 0 times[x7,x5] ) Which of these options is better depends on the situation, particularly on what you want to do with the result. Hope this helps. Regards, Leonid On Sat, Apr 24, 2010 at 1:02 AM, Robert Wright <mathematicauser1 at yahoo.com>wrote: > I am using a Graph Theory algorithm which requires that I multiply an > edge-weighted adjacency matrix with symbolic parts. In my problem, the order > of the symbols corresponds to the edges that make up a path - for example, > x2 x1 x7 would indicate that the path progresses from x2 to x1 then x7. The > snag comes when Mathematica reorders the symbols in each expression > appearing in the matrix result from multiplying Ci x Cj - is there a way of > stopping this from happening? > > Here is some code that illustrates the problem: > > C1 = {{0, x1, 0, 0}, {x2, 0, x3, 0}, {x4, 0, 0, x5}, {x6, 0, x7, 0}}; > C2 = C1.C1; > MatrixForm@C2 > > The MatrixForm output shows how Mathematica has sequenced the symbols in > 'ascending' order. In my case, I want to preserve the order of the symbols > in the calculated expression: so, for example, row 4 of C1 times column 2 of > C1 should give x4 x1 and not x1 x4. How do I stop Mathematicafrom reordering > the resulting expression? >