Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the second return value from a function without using temporary variables?

Tags:

matlab

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))) 
like image 224
jjkparker Avatar asked Sep 14 '10 15:09

jjkparker


People also ask

How do you capture a value returned from a function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.

What gets returned from a function without a return statement?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

How do I return a value from one function to another in python?

Simply call a function to pass the output into the second function as a parameter will use the return value in another function python.

Can a function return two values by Yes No?

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.


2 Answers

not that i know of. subsref doesn't seem to work in this case, possibly because the second variable isn't even returned from the function.

since matlab 2009b it is possible to use the notation

[~, b] = function(x)  

if you don't need the first argument, but this still uses a temporary variable for b.

like image 51
second Avatar answered Oct 11 '22 10:10

second


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?.

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 

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)) 
like image 40
gnovice Avatar answered Oct 11 '22 12:10

gnovice