【问题标题】:Matlab's Inline function in PythonPython中的Matlab内联函数
【发布时间】:2014-05-14 07:53:10
【问题描述】:

在Matlab中,我们可以做到

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

我们有类似 Python 中的 inline 的函数吗?

【问题讨论】:

    标签: python matlab numpy inline


    【解决方案1】:

    我认为“内联”的 python 等效项是 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】:

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

      % pylab inline
      

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

      【讨论】:

      • 我编辑了,你只需要一个 % 符号。您只需在笔记本的一个单元格中键入此行,然后执行该单元格。这必须在导入 pylab 或 matplotlib 之前完成。
      • 鉴于其他回复,此内联可能不是您要的...
      【解决方案3】:

      您可以使用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)
      

      或者假设你的函数中的变量总是被称为 x

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

      【讨论】:

      • eval 太冒险了——尤其是当你要求用户输入时!
      • @TonySuffolk66 你是对的。我会将其添加到答案中。
      【解决方案4】:

      这是不一样的,因为 lambda 做其他事情,我只想替换我的变量 F 在 GRAD 中的值,但使用“内联”,这段代码是 matlab 的:

      F= 3*X**2+2*X*Y+4*(Y-2)**2  
      GRAD= inline([diff(F,X), diff(F,Y)])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-12
        • 2014-06-27
        • 2017-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-04
        • 2011-07-13
        相关资源
        最近更新 更多