如何在不使用临时变量的情况下从函数中获取第二个返回值? [英] How do I get the second return value from a function without using temporary variables?

查看:105
本文介绍了如何在不使用临时变量的情况下从函数中获取第二个返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回两个值的函数,如下所示:

I have a function that returns two values, like so:

[a b] = myfunc(x)

有没有一种方法可以在不使用临时变量且不更改函数的情况下获得第二个返回值?

Is there a way to get the second return value without using a temporary variable, and without altering the function?

我正在寻找的东西是这样的:

What I'm looking for is something like this:

abs(secondreturnvalue(myfunc(x)))

推荐答案

除非迫切需要这样做,否则我建议不要这样做.代码的清晰度会受到影响.将输出存储在临时变量中,然后将这些变量传递给另一个函数将使您的代码更整洁,此处概述了实现此目的的不同方法:

Unless there is some pressing need to do this, I would probably advise against it. The clarity of your code will suffer. Storing the outputs in temporary variables and then passing these variables to another function will make your code cleaner, and the different ways you could do this are outlined here: How to elegantly ignore some return values of a MATLAB function?.

但是,如果您真的想要或需要执行此操作,那么我想到的唯一可行的方法是创建自己的函数secondreturnvalue.这是一个更通用的示例,称为nth_output:

However, if you really want or need to do this, the only feasible way I can think of would be to create your own function secondreturnvalue. Here's a more general example called nth_output:

function value = nth_output(N,fcn,varargin)
  [value{1:N}] = fcn(varargin{:});
  value = value{N};
end

您可以通过以下方式调用它:1)所需的输出参数编号,2) ="noreferrer">函数句柄,以及3)需要传递给myfunc的任何输入参数:

And you would call it by passing as inputs 1) the output argument number you want, 2) a function handle to myfunc, and 3) whatever input arguments you need to pass to myfunc:

abs(nth_output(2,@myfunc,x))

这篇关于如何在不使用临时变量的情况下从函数中获取第二个返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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