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

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

问题描述

假设我想从返回两个输出的 m-file-function 创建一个匿名函数.是否可以设置匿名函数,使其仅返回 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)

推荐答案

匿名函数 让它选择从具有多个可能输出参数的函数返回哪个输出.但是,当您评估匿名函数时,您可以返回多个输出.下面是一个使用函数 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)

此外,处理您上面给出的特定示例的最佳方法实际上只是使用 函数句柄 @ttest2 作为CELLFUN,然后从 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天全站免登陆