0

有没有办法概括以下内容?(注意:nargout_requested除了运行时可能不知道

function outputs = apply_and_gather(f, args, nargout_requested)
  switch nargout_requested
    case 0
      f(args{:});
      outputs = {};
    case 1
      o1 = f(args{:});
      outputs = {o1};
    case 2
      [o1,o2] = f(args{:});
      outputs = {o1,o2};
    case 3
      [o1,o2,o3] = f(args{:});
      outputs = {o1,o2,o3};
      ...

换句话说,我想调用一个带有参数元胞数组的函数,并将函数的输出分配给一个元胞数组,并请求一定数量的输出参数。

在 python 中,这只是:

outputs = f(*args)

但是 Matlab 要求你在调用函数之前告诉函数你想要多少个参数,如果你有太多的输出参数,就会给你一个错误。

4

2 回答 2

2

啊哈,我想我有。我仍然必须对零和非零之间的输出数量进行特殊处理:

function outputs = apply_and_gather(f, args, nargout_requested)
switch nargout_requested
    case 0
        f(args{:});
        outputs = {};
    otherwise
        outputs = cell(1, nargout_requested);
        [outputs{:}] = f(args{:});
end

示例用法:

>> outputs=apply_and_gather(@polyfit,{[0:0.1:1 1.1],[0:0.1:1 1],3},3)

outputs = 

    [1x4 double]    [1x1 struct]    [2x1 double]

如果我不是零输出参数的特殊情况,我会得到:

>> outputs=apply_and_gather2(@polyfit,{[0:0.1:1 1.1],[0:0.1:1 1],3},0)
The left hand side is initialized and has an empty range of indices.
However, the right hand side returned one or more results.

Error in apply_and_gather2 (line 3)
    [outputs{:}] = f(args{:});
于 2013-06-05T00:51:14.970 回答
0

要调用另一个函数,请求可变数量的输出,请使用一些不明显的语法魔术,如下所示:

function outputs=  = apply_and_gather(f, args, nargout_requested)
    outputs= cell(1, requested);  %Preallocate to define size
    [outputs{:}] = f(args{:});

要返回可变数量的参数,请查看varargout. 您的代码如下所示:

function varargout =  = apply_and_gather(f, args, nargout_requested)
    varargout = cell(1, requested);

    % ... your code here, setting values to the varargout cell
于 2013-06-05T01:02:00.100 回答