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)))
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.
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.
Simply call a function to pass the output into the second function as a parameter will use the return value in another function python.
No, you can not have two returns in a function, the first return will exit the function you will need to create an object.
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
.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With