Matlab的Python内联函数

时间:2021-07-14 02:08:52

In Matlab, we can do

在Matlab中,我们可以做到

x = -10:.1:10;
f = inline('normpdf(x,3,2) + normpdf(x,-5,1)','x');
t = plot(x,f(x))

Do we have a similar function like inline in Python?

我们有像Python中的内联类似的功能吗?

3 个解决方案

#1


5  

I think the python equivalent of "Inline" would be lambda

我认为python相当于“Inline”将是lambda

 Matlab:
 f = inline('normpdf(x,3,2) + normpdf(x,-5,1)','x');

 python:
 f = lambda x : normpdf(x,3,2) + normpdf(x,-5,1)
 # Assuming that normpdf is defined and in scope ;-)

#2


2  

Yes, in iPython notebook (and maybe Enthought Canopy?), you can set inline using the "magic function"

是的,在iPython笔记本(也许是Enthought Canopy?)中,您可以使用“魔术功能”设置内联

% pylab inline

You must restart the kernel for it to take effect (at least for iPython notebook versions anterior to 2.0)

您必须重新启动内核才能使其生效(至少对于2.0之前的iPython笔记本版本)

#3


0  

You can use eval, which is a dangerous function (see e.g. http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html):

您可以使用eval,这是一项危险的功能(请参阅http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html):

from numpy import *
x = np.arange(0, pi, 0.1)
f = eval('sin') # fill in any function
y = f(x)

or like assuming that the variable in your finction is always referred to as x

或者假设你的指令中的变量总是被称为x

from numpy import *
x = np.arange(0, pi, 0.1)
y = eval('sin(x)')

#1


5  

I think the python equivalent of "Inline" would be lambda

我认为python相当于“Inline”将是lambda

 Matlab:
 f = inline('normpdf(x,3,2) + normpdf(x,-5,1)','x');

 python:
 f = lambda x : normpdf(x,3,2) + normpdf(x,-5,1)
 # Assuming that normpdf is defined and in scope ;-)

#2


2  

Yes, in iPython notebook (and maybe Enthought Canopy?), you can set inline using the "magic function"

是的,在iPython笔记本(也许是Enthought Canopy?)中,您可以使用“魔术功能”设置内联

% pylab inline

You must restart the kernel for it to take effect (at least for iPython notebook versions anterior to 2.0)

您必须重新启动内核才能使其生效(至少对于2.0之前的iPython笔记本版本)

#3


0  

You can use eval, which is a dangerous function (see e.g. http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html):

您可以使用eval,这是一项危险的功能(请参阅http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html):

from numpy import *
x = np.arange(0, pi, 0.1)
f = eval('sin') # fill in any function
y = f(x)

or like assuming that the variable in your finction is always referred to as x

或者假设你的指令中的变量总是被称为x

from numpy import *
x = np.arange(0, pi, 0.1)
y = eval('sin(x)')