【问题标题】:How do you get "matlab style" function output in python如何在 python 中获得“matlab 风格”函数输出
【发布时间】:2013-11-24 06:15:21
【问题描述】:

我的问题是针对 matlab 函数的第一行

function [a, b, c, d] = somefunction(arg1, arg2, arg3)
    % Some mangoes and pears
end

特别是在该等式的左侧。这样,matlab(我认为?)确保输出是那个向量。我知道在 Python 中,您可以通过将计算结果组合成一个数组来实现相同的目的。有没有办法可以在 python 中获得这种“快捷方式”方法?像这样(但显然不完全是这样):

def somefunction(arg1,arg2,arg3) = [a, b, c, d]:
# some apples and bananas

【问题讨论】:

    标签: python matlab numpy


    【解决方案1】:

    在 python (AFAIK) 中,您使用return 命令定义返回值。

    所以在 Matlab 中

    function [a, b, c, d] = foo( a1, a2 )
    % apples banabs, and most importantly assignment to outputs:
    a = ...
    b = ...
    c = ...
    d = ...
    return;   % return has no arguments in Matlab
    

    在python中:

    def foo( a1, a2 ) :
        % apples bananas
        return a, b, c, d # outputs are defined here
    
    如果你希望你的输出作为一个元组,你可以明确地做到这一点
    
        return ( a, b, c, d ) 
    

    【讨论】:

    • 那么它在 matlab 中说 [vector]=somefunction(args) 的唯一一件事就是“占位”要返回的值?
    • @NormanB 是的。这:a, b = function( a1, a2 ) 是 Matlab 中的语法错误。你必须写[a, b] = function( a1, a2 )
    • 我担心return a, b, c, dreturn (a, b, c, d) 是完全一样的,只是括号多了。两者都返回一个元组。
    • @Hyperboreus 您将输出分配给多少个参数? t = foo( a1, a2 )a, b, c, d = foo(a1, a2)?
    • @Shai 没有任何区别。 type(foo(a1,a2))tuple。因此,在您的第一个示例中,t 将是一个元组,而在您的第二个示例中,它将被解包。至少def f (): return 1,2,3def g(): return (1,2,3) 的返回类型是相同的。
    猜你喜欢
    • 2014-12-16
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    相关资源
    最近更新 更多