有没有办法概括以下内容? (注意:除了在运行时)
,可能无法识别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要求您在调用之前告诉函数您需要多少个参数,如果输出参数太多,则会给出错误。
答案 0 :(得分: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{:});
答案 1 :(得分: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