Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

controlling order of variables in an expression

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

like image 764
kirill_igum Avatar asked Jan 21 '23 06:01

kirill_igum


1 Answers

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]
like image 50
Simon Avatar answered Feb 11 '23 16:02

Simon