Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

wolfram mathematica - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...