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

前端 未结 2 429
清歌不尽
清歌不尽 2020-11-29 10:48

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 tempora

相关标签:
2条回答
  • 2020-11-29 11:32

    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.

    0 讨论(0)
  • 2020-11-29 11:35

    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))
    
    0 讨论(0)
提交回复
热议问题