在matlab中非冗长地转发varargout

时间:2017-02-12 16:34:11

标签: matlab

我有一个matlab函数,如:

function [f, fdx] = twice(x)
    f = x * 2;
    if nargout > 1
       fdx = 2;
    end
end

我想从另一个函数调用此函数,保留可选的第二个参数语义。然而,这很麻烦:

function [g, gdx] = twiceplusinverse(x)
    % this starts to get messy if the arguments to double are long
    if nargout > 1
       [f, fdx] = twice(x);
    else
       f = double(x)
    end

    g = f + 1/x;
    if narargout > 1
        gdx = fdx + -1/x^2;
    end
end

如何避免重复具有多个返回值的每个函数调用?如何编写不违反DRY的以下内容?

if nargout > 1
    [f, fda, fdb, fdc] = longfunction(some_func_producing_a(), b, another_func_for_c());
else
    f = longfunction(somefunc_like_above(), b, another_func_for_c());
end

1 个答案:

答案 0 :(得分:2)

您可以使用varargout作为函数的输出,然后使用逗号分隔列表来指定其他函数的输出。由于您使用1:nargout作为逗号分隔列表中的索引,因此从您的函数请求的输出参数数将自动传递给另一个函数。

function varargout = myfunc(x)
    [varargout{1:nargout}] = other_func(x);
end
相关问题