如何通过附加到 Mathematica 中的函数来重新定义函数?
在 Mathematica 中进行计算时,我经常需要通过附加到函数来重新定义函数。例如,如果我定义
f[n_] := n^2 + n + 1
then 一段时间后我想添加 2n^3 那么从现在开始
f[n] = 2n^3 + n^2 + n + 1.
然后我想添加 Sin[n] 并进一步
f[n] = 2n^3 + n^2 + n + 1 + Sin[n].
依此类推。
使用变量很容易,例如 x += 2。函数有类似的东西吗?…
编辑添加 – 是的,我这样做是为了半手动地找到最适合数据的函数。我知道有一些函数可以做到这一点,但我想看看我自己是否可以实现这一点。我这样做了,但方式并不优雅,所以引发了这个问题。
When doing calculations in Mathematica I often need to redefine a function by appending to it. For example if I define
f[n_] := n^2 + n + 1
then after some time I'd like to add 2n^3 so from now on
f[n] = 2n^3 + n^2 + n + 1.
Then I'd like to add Sin[n] and going further
f[n] = 2n^3 + n^2 + n + 1 + Sin[n].
And so on.
It's easy to do with variables, for example x += 2. Is there something similar for functions?…
Edited to add – yes, I was doing that to semi-manually find a function that fits data the best. I know there are functions to do that but I wanted to see if I can get there myself. I did that but the way was not elegant so that prompted this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以定义基本函数列表,然后只需选择所需数量的元素:
You can define a list of your basis functions and then just pick up needed number of elements:
一个迟到的解决方案:下面的代码使用了一个辅助函数,并且要为所有后续使用添加一个术语,您只需调用一个函数一次,第二个参数是表达您想要的术语的纯函数添加:
使用示例:
使用这种方法时,当您想要将术语添加到函数中时,您应该小心地仅调用双参数形式一次 - 否则每次调用时都会添加该术语。
A late-to-the-party solution: the code below uses an auxiliary function, and to add a term for all subsequent uses, you just have to call a function once, with a second parameter being a pure function expressing the term you want to add:
Examples of use:
With this approach, you should be careful though to call the two-argument form only once, when you want to add the term to the function - or it will be added every time you call.
你的问题背后有很多微妙之处。我是说,怪物的微妙之处。
我不会输入曲折,但您可以执行以下操作:
因此,例如绘制此图:
但是,您不应该这样做。详细了解延迟定义!
There are many subtleties craving under your question. Monster subtleties, I mean.
I'll not enter the meander, but you may do something like:
So, for example for plotting this:
However, you should NOT do this. Read more about delayed definition!
这实际上取决于您为什么需要重新定义函数
f
。如果原因是您意识到之前的定义是错误的,那么无论如何只需返回到有问题的单元格,编辑它并重新评估它以重新定义f
。变为
注意
:=
语法和下划线。相反,如果您希望
f
采用第一个定义,例如n<=100
和第二个定义n>100
,您将使用Condition语法/;
,如下所示。It really depends why you need to redefine your function
f
. If the reason is that you realised the previous definition was wrong, then by all means just go back to the cell in question, edit it and re-evaluate it to re-definef
.Becomes
Note the
:=
syntax and the underscore.If, instead, you want
f
to take the first definition for, sayn<=100
and the second forn>100
, you would use the Condition syntax/;
, as shown below.这可行,但需要单独的函数。推广追加函数并不那么容易。
This works, but requires separate functions. Generalising the append function is not so easy.