在MATLAB中使用匿名函数跳过输出 [英] Skipping outputs with anonymous function in MATLAB

查看:66
本文介绍了在MATLAB中使用匿名函数跳过输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I want to create an anonymous function from a m-file-function that returns two outputs. Is it possible to set up the anonymous function such that it only returns the second output from the m-file-function?

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

Example: ttest2 returns two outputs, t/f and a probability. If I want to use the t-test with cellfun, I might only be interested in collecting the probabilities, i.e. I'd like to write something like this

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

推荐答案

中,我没有办法知道. uk/access/helpdesk/help/techdoc/matlab_prog/f4-70115.html"rel =" noreferrer>匿名函数,让它选择从具有多个可能输出参数的函数返回哪个输出.但是,当您评估匿名函数时,您可以返回多个输出.这是使用 MAX 的示例:

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:

>> 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)

另外,处理上面给出的特定示例的最佳方法是实际上仅使用 CELLFUN ,然后从

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:

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

在较新版本的MATLAB上,可以将变量junk替换为

On newer versions of MATLAB, you can replace the variable junk with ~ to ignore the first output argument.

这篇关于在MATLAB中使用匿名函数跳过输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆