AFAIK,您不能仅使用内联匿名函数来执行此操作,因为 Matlab 语法不提供在单个表达式中捕获函数的多个输出并对其进行索引的方法。但是您可以编写几个可重用的辅助函数来执行此操作,然后使用它们定义匿名函数。
假设您的四个参数输出函数名为“f4”。
function varargout = f4(x)
%F4 Dummy function that returns 4 argouts holding identifying indexes
varargout = num2cell(1:4);
这是一个可重用的辅助函数,用于重新映射函数调用的输出。
function varargout = callandmap(fcn, ix, varargin)
%CALLANDMAP Call a function and rearrange its output arguments
tmp = cell(1,max(ix)); % Capture up to the last argout used
[tmp{:}] = fcn(varargin{:}); % Call the original function
varargout = tmp(ix); % Remap the outputs
现在您可以创建像这样的匿名参数重映射函数。在这里,g 持有一个匿名函数,它采用与原始函数相同的输入,但只返回其原始 4 个输出中的 2 个。
>> g = @(varargin) callandmap(@f4, [2 4], varargin{:})
g =
@(varargin)callandmap(@f4,[2,4],varargin{:})
>> [a,b] = g('dummy') % gets argouts 2 and 4 from original f4() function
a =
2
b =
4
>>
使用 varargin 允许您在调用结果函数句柄时省略尾随参数。如果您知道将始终提供所有argins,则可以根据需要使用命名argins以提高可读性。
你可以变得更奇特,用一个闭包来做到这一点。
function fcn = mapargout(fcnIn, ixArgout)
%MAPARGOUT Create wrapper function that selects or reorders argouts
%
% fcn = argoutselector(fcnIn, ixArgout)
%
% Wraps a given function handle in a function that rearranges its argouts.
% This uses closures so it may have performance impacts.
%
% FcnIn is a function handle to wrap.
%
% IxArgout is a list of indexes in to the original functions argout list
% that should be used as the outputs of the new function.
%
% Returns a function handle to a new function.
fcn = @extractor;
function varargout = extractor(varargin)
n = max(ixArgout);
tmp = cell(1,n);
% Call the wrapped function, capturing all the original argouts
[tmp{:}] = fcnIn(varargin{:});
% And then select the ones you want
varargout = tmp(ixArgout);
end
end
这使得创建匿名函数的代码更加简单。您可以将其与其他函数包装器调用组合起来。
>> g = mapargout(@f4, [2 4])
g =
@mapargout/extractor
>> [a,b] = g('dummy')
a =
2
b =
4
>>
但在 Matlab 中使用闭包可能会很棘手,并且可能会对性能产生影响。除非您需要额外的功能,否则 callandmap 方法可能更可取。