首页 文章

如何直接将函数的多个输出传递给另一个?

提问于
浏览
0

让我详细说明 examples: 我们知道如何轻松地将函数与单个输出组合:

a = sin(sqrt(8));

现在考虑这个示例代码包含两个步骤来计算 R ,其中 XY 作为中间输出 .

[X, Y] = meshgrid(-2:2, -2:2);
[~, R] = cart2pol(X, Y);

In general 有没有办法结合这两个函数并摆脱中间输出?例如,我如何编写类似于 [~, R] = cart2pol(meshgrid(-2:2, -2:2)) 的东西,它与前面的代码一样?

Note: 我的问题与this question的不同之处在于,在我的情况下,外部函数接受多个输入 . 因此,我不能也不想将第一个函数的输出组合成一个单元格数组 . 我希望它们分别传递给第二个函数 .

1 回答

  • 2

    To answer the question in the title: 使用以下函数,可以将函数的多个输出重定向到另一个:

    function varargout = redirect(source, destination, n_output_source, which_redirect_from_source, varargin)
    %(redirect(source, destination, n_output_source, which_redirect_from_source,....)
    %redirect output of a function (source) to input of another function(destination)
    % source: function pointer
    % destination: function pointer
    % n_output_source: number of outputs of source function (to select best overload function)
    % which_redirect_from_source: indices of outputs to be redirected
    % varargin arguments to source function
        output = cell(1, n_output_source);
        [output{:}] = source(varargin{:});
        varargout = cell(1, max(nargout,1));
        [varargout{:}] = destination(output{which_redirect_from_source});
    end
    

    现在我们可以将它应用于示例:

    [~,R] = redirect(@meshgrid,@cart2pol, 2, [1, 2], -2:2, -2:2)
    

    这里,源函数有2个输出,我们想要将输出1和2从源重定向到目标 . -2:2是源函数的输入参数 .


    Other way to deal with the mentioned example: 如果您可以使用GNU Octave,使用 bsxfunnthargout 这是您的解决方案:

    R = bsxfun(@(a,b) nthargout(2, @cart2pol,a,b),(-2:2)',(-2:2))
    

    在Matlab中,一个可能的解决方案是:

    [~, R] = cart2pol(meshgrid(-2:2), transpose(meshgrid(-2:2)))
    

    要么

    function R = cart2pol2(m)
        [~,R] = cart2pol(m,m')
    end
    
    cart2pol2(meshgrid(-2:2, -2:2))
    

相关问题