在MATLAB中使用匿名函数跳过输出

Jon*_*nas 16 matlab anonymous-function

假设我想从一个返回两个输出的m文件函数创建一个匿名函数.是否可以设置匿名函数,使其仅返回m文件函数的第二个输出?

示例:ttest2返回两个输出,t/f和概率.如果我想使用t检验cellfun,我可能只对收集概率感兴趣,即我想写这样的东西

probabilities = cellfun(@(u,v)ttest2(u,v)%take only second output%,cellArray1,cellArray2)
Run Code Online (Sandbox Code Playgroud)

gno*_*ice 15

我不知道匿名函数的表达式中让它选择从具有多个可能输出参数的函数返回哪个输出.但是,在评估匿名函数时,可以返回多个输出.这是使用函数MAX的示例:

>> data = [1 3 2 5 4];  %# Sample data
>> fcn = @(x) max(x);   %# An anonymous function with multiple possible outputs
>> [maxValue,maxIndex] = fcn(data)  %# Get two outputs when evaluating fcn

maxValue =

     5         %# The maximum value (output 1 from max)


maxIndex =

     4         %# The index of the maximum value (output 2 from max)
Run Code Online (Sandbox Code Playgroud)

另外,处理上面给出的具体示例的最佳方法是实际上只使用函数句柄 @ttest2作为CELLFUN的输入,然后从CELLFUN本身获取多个输出:

[junk,probabilities] = cellfun(@ttest2,cellArray1,cellArray2);
Run Code Online (Sandbox Code Playgroud)

在MATLAB的新版本,你可以替换变量junk~忽略第一个输出参数.