控制表达式中变量的顺序 [英] controlling order of variables in an expression

查看:26
本文介绍了控制表达式中变量的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Mathematica 中,如何更改变量的重要性顺序?例如:如果我输入 b+c+a+d,我得到 a+b+c+d 但我希望 b 和 d 位于其他变量之前.所以我得到 b+d+a+c

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

推荐答案

首先你需要定义一个排序函数,如:

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.

然后您可以使用

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]

这篇关于控制表达式中变量的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆