简体   繁体   English

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

[英]Skipping outputs with anonymous function in MATLAB

Say I want to create an anonymous function from a m-file-function that returns two outputs. 假设我想从返回两个输出的m文件函数创建一个匿名函数。 Is it possible to set up the anonymous function such that it only returns the second output from the m-file-function? 是否可以设置匿名函数,使其仅返回m文件功能的第二个输出?

Example: ttest2 returns two outputs, t/f and a probability. 示例: ttest2返回两个输出,t / f和一个概率。 If I want to use the t-test with cellfun , I might only be interested in collecting the probabilities, ie I'd like to write something like this 如果我想对cellfun使用t检验,我可能只对收集概率感兴趣,即我想写这样的东西

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

There's no way I know of within the expression of the anonymous function to have it select which output to return from a function with multiple possible output arguments. 我无法在匿名函数 的表达式中知道让它选择从具有多个可能输出参数的函数返回哪个输出。 However, you can return multiple outputs when you evaluate the anonymous function. 但是,当您评估匿名函数时,您可以返回多个输出。 Here's an example using the function MAX : 这是使用函数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)

Also, the best way to handle the specific example you give above is to actually just use the function handle @ttest2 as the input to CELLFUN , then get the multiple outputs from CELLFUN itself: 此外,为了处理您在上面给出的具体例子中,最好的办法是实际上只是使用功能手柄 @ttest2作为输入到CELLFUN ,然后从获得多个输出CELLFUN本身:

[junk,probabilities] = cellfun(@ttest2,cellArray1,cellArray2);

On newer versions of MATLAB, you can replace the variable junk with ~ to ignore the first output argument. 在较新版本的MATLAB上,可以将变量junk替换为~以忽略第一个输出参数。

One way to do this is to define the function: 一种方法是定义函数:

function varargout = getOutput(func,outputNo,varargin)
    varargout = cell(max(outputNo),1);
    [varargout{:}] = func(varargin{:});
    varargout = varargout(outputNo);
end

and then getOutput(@ttest2,2,u,v) gives only the p-value . 然后getOutput(@ttest2,2,u,v)仅给出p-value

To use it in a cellfun you would need to run: 要在cellfun使用它,您需要运行:

probabilities = cellfun(@(u,v)getOutput(@ttest2,2,u,v)...

This eliminates the need to write a wrapper every time, but then you have to make sure this function is always in the path. 这样就无需每次都编写包装器,但是您必须确保此函数始终在路径中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM