在 Mathematica 中定义自定义符号 [英] Define Custom Notation in Mathematica

查看:27
本文介绍了在 Mathematica 中定义自定义符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要提取以将值列表限制为子列表,即如果 vals 给出 vars={x1,x2,x3,x4} 的值,我需要svars={x2,x4} 的值我做 restrict[list,vars,svars] where

restrict[vars_, svars_, vals_] :=Extract[vals, Flatten[Position[vars, #] &/@ svars, 1]]

我想提高代码的可读性,也许通过为 restrict[vars,svars,vals]

定义以下自定义符号


(来源:yaroslavvb.com)

我的问题是

  1. 实现这一目标的好方法是什么?
  2. 这完全是个好主意吗?

解决方案

好的符号非常有用 - 但我不确定是否需要这个特殊的符号...

也就是说,Notation 包使这很容易.由于使用 Notation 面板时有很多隐藏框,我将使用屏幕截图:

您可以使用 Action -> 查看底层的 NotationMake* 下值构造.PrintNotationRules 选项.在[4]中截图生成

NotationMakeExpression[SubscriptBox[vals_, RowBox[{vars_, "|", svars_}]], StandardForm] :=MakeExpression[RowBox[{"restrict", "[", RowBox[{vars, ",", svars, ",", vals}],]}], 标准格式]NotationMakeBoxes[下标[vals_, vars_ |svars_], StandardForm] :=SubscriptBox[MakeBoxes[vals, StandardForm],RowBox[{Parenthesize[vars, StandardForm, Alternatives], "|",括号[svars, StandardForm, Alternatives]}]]

I often need to extract to restrict value lists to sublists, ie if vals gives values of vars={x1,x2,x3,x4}, and I need values of svars={x2,x4} I do restrict[list,vars,svars] where

restrict[vars_, svars_, vals_] := 
 Extract[vals, Flatten[Position[vars, #] & /@ svars, 1]]

I'd like to improve code readability, perhaps by defining following custom notation for restrict[vars,svars,vals]


(source: yaroslavvb.com)

My questions are

  1. What is a good way to implement this?
  2. Is this a good idea altogether?

解决方案

Good notations can be very useful - but I'm not sure that this particular one is needed...

That said, the Notation package makes this pretty easy. As there are many hidden boxes when you use the Notation palette, I'll use a screenshot:

You can see the underlying NotationMake* downvalues construct by using the Action -> PrintNotationRules option. In[4] in the screenshot generates

NotationMakeExpression[
  SubscriptBox[vals_, RowBox[{vars_, "|", svars_}]], StandardForm] := 
 MakeExpression[
  RowBox[{"restrict", "[", RowBox[{vars, ",", svars, ",", vals}], 
    "]"}], StandardForm]

NotationMakeBoxes[Subscript[vals_, vars_ | svars_], StandardForm] := 
 SubscriptBox[MakeBoxes[vals, StandardForm], 
  RowBox[{Parenthesize[vars, StandardForm, Alternatives], "|", 
    Parenthesize[svars, StandardForm, Alternatives]}]]

这篇关于在 Mathematica 中定义自定义符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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