查看单个帖子
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 在MATLAB中使用匿名函数跳过输出

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

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

probabilities = cellfun(@(u,v)ttest2(u,v)%take only second output%,cellArray1,cellArray2)

回答:

我无法在匿名函数 的表达式中知道让它选择从具有多个可能输出参数的函数返回哪个输出。但是,当您评估匿名函数时,您可以返回多个输出。这是使用函数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) 此外,为了处理您在上面给出的具体例子中,最好的办法是实际上只是使用功能手柄 @ttest2作为输入到CELLFUN ,然后从获得多个输出CELLFUN本身:

[junk,probabilities] = cellfun(@ttest2,cellArray1,cellArray2); 在较新版本的MATLAB上,可以将变量junk替换为~以忽略第一个输出参数。



更多&回答...
poster 当前离线   回复时引用此帖