tags:

views:

85

answers:

3

In Mathematica, how do you change the order of importance of variables? for example: if i enter b+c+a+d, i get a+b+c+d but i want b and d to preceed other variables. so that i get b+d+a+c

note, i'd like to use it where + is non-commutative

+1  A: 

So, don't use "+", because Plus[] IS commutative.

Define your own myPlus[x_,y_]:= .... whatever.

If you have an idea of what your new Plus[] should do, post it and we may try to help you with the definition/

HTH!

PS> You may change the definition of Plus[] ... but :)

belisarius
Probably best if you use something like CirclePlus - because it already has nice infix notation assigned to it.
Simon
-1, no attempt to answer the question
rcollyer
+2  A: 

First you need to define an ordering function like:

In[1]:= CPOrdering[a]=3;
CPOrdering[b]=1;
CPOrdering[d]=2;
CPOrdering[c]=4;

Although, for more complicated examples, you should probably be smarter about it than this - ie use pattern matching.

Then you can sort expressions using

In[5]:= CirclePlus[a,b,c,d]
SortBy[%,CPOrdering]
Out[5]= a\[CirclePlus]b\[CirclePlus]c\[CirclePlus]d
Out[6]= b\[CirclePlus]d\[CirclePlus]a\[CirclePlus]c

This can then be automated using something like

CPOrdering[a_, b_] := CPOrdering[a] < CPOrdering[b]
CirclePlus[a__] /; (!OrderedQ[{a}, CPOrdering]) := CirclePlus@@SortBy[{a}, CPOrdering]
Simon
+1 very clean! One more char to go ...
belisarius
+1  A: 

The underlying reason b+c+a+d becomes a+b+c+d in Mathematica is because Plus has the attribute Orderless. In general, a symbol f with attribute Orderless means that the elements of f in an expession f[e1, e2, e3], the elements ei should be sorted into canonical order, and in particular, Mathematica's canonical order equivalent to that of OrderedQ and Ordering.

Orderless is even accounted for during pattern matching:

In[47]:= a+b+c+d /. a+c -> e
Out[47]= b+d+e

It's highly, highly recommended that you do NOT remove the Orderless attribute from Plus because the consequences could be dire for lots of functionality in Mathematica.

As other posters have noted, your best bet is to simply define your own function that is NOT Orderless, and will therefore preserve argument order. You might also find HoldForm useful in very limited circumstances.

Also note that nothing stops you from typesetting symbols in an expression in whatever order you want in a notebook, as long as you don't evaluate-in-place, etc.

Michael Pilat