【问题标题】:How to directly pass multiple outputs of a function to another?如何将一个函数的多个输出直接传递给另一个?
【发布时间】:2017-01-14 12:36:39
【问题描述】:

让我用示例详细说明:我们知道如何轻松地将函数与单个输出相结合:

a = sin(sqrt(8));

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

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

一般有没有办法将这两个功能结合起来并摆脱中间输出?例如,我怎样才能编写类似于[~, R] = cart2pol(meshgrid(-2:2, -2:2)) 的代码,并且与之前的代码工作方式相同?

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

【问题讨论】:

  • 如果你想要一个特定的答案只是为了这个例子,cart2pol 函数需要 2 个输入,并且通过给它网格网格[X Y] 的输出,你给它一个单一的矩阵作为输入。
  • 其实我只是想举个例子,提一下cart2pol。我会修改我的帖子。
  • @EBH 差异解释。

标签: matlab function arguments octave


【解决方案1】:

回答标题中的问题:使用以下函数,可以将一个函数的多个输出重定向到另一个:

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 是源函数的输入参数。


处理上述示例的其他方法:如果您可以使用 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))

【讨论】:

  • 虽然这个解决方案可能有效,但看起来并没有好很多。两条线的方法至少让未来的用户清楚你在做什么。
  • @Bernhard 我同意。 Matlab 语言的流行很大程度上归功于它的表现力。但是,此答案是作为一种解决方法提供的
猜你喜欢
  • 2021-12-26
  • 2012-08-02
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 2011-06-09
相关资源
最近更新 更多