poster
2019-12-10, 20:41
假设我想从返回两个输出的m文件函数创建一个匿名函数。是否可以设置匿名函数,使其仅返回m文件功能的第二个输出?
示例: ttest2返回两个输出,t / f和一个概率。如果我想对cellfun使用t检验,我可能只对收集概率感兴趣,即我想写这样的东西
probabilities = cellfun(@(u,v)ttest2(u,v)%take only second output%,cellArray1,cellArray2)
回答:
我无法在匿名函数 (http://www.mathworks.co.uk/access/helpdesk/help/techdoc/matlab_prog/f4-70115.html) 的表达式中知道让它选择从具有多个可能输出参数的函数返回哪个输出。但是,当您评估匿名函数时,您可以返回多个输出。这是使用函数MAX (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/max.html)的示例:
>> 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) 此外,为了处理您在上面给出的具体例子中,最好的办法是实际上只是使用功能手柄 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/function_handle.html) @ttest2作为输入到CELLFUN (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cellfun.html) ,然后从获得多个输出CELLFUN (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cellfun.html)本身:
[junk,probabilities] = cellfun(@ttest2,cellArray1,cellArray2); 在较新版本的MATLAB上,可以将变量junk替换为~ (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/bresuxt-1.html#br67dkp-1)以忽略第一个输出参数。
更多&回答... (https://stackoverflow.com/questions/3096281)
示例: ttest2返回两个输出,t / f和一个概率。如果我想对cellfun使用t检验,我可能只对收集概率感兴趣,即我想写这样的东西
probabilities = cellfun(@(u,v)ttest2(u,v)%take only second output%,cellArray1,cellArray2)
回答:
我无法在匿名函数 (http://www.mathworks.co.uk/access/helpdesk/help/techdoc/matlab_prog/f4-70115.html) 的表达式中知道让它选择从具有多个可能输出参数的函数返回哪个输出。但是,当您评估匿名函数时,您可以返回多个输出。这是使用函数MAX (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/max.html)的示例:
>> 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) 此外,为了处理您在上面给出的具体例子中,最好的办法是实际上只是使用功能手柄 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/function_handle.html) @ttest2作为输入到CELLFUN (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cellfun.html) ,然后从获得多个输出CELLFUN (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cellfun.html)本身:
[junk,probabilities] = cellfun(@ttest2,cellArray1,cellArray2); 在较新版本的MATLAB上,可以将变量junk替换为~ (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/bresuxt-1.html#br67dkp-1)以忽略第一个输出参数。
更多&回答... (https://stackoverflow.com/questions/3096281)