开发者

controlling order of variables in an expression

In Mathematica, how do you change the order of importance of variables? for example: if i enter 开发者_JAVA技巧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


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]


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.


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜