octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

nthoutarg function?


From: John W. Eaton
Subject: nthoutarg function?
Date: Fri, 14 Oct 2011 11:32:25 -0400

On 14-Oct-2011, Jordi Gutiérrez Hermoso wrote:

| This blog post got me thinking:
| 
|     http://abandonmatlab.wordpress.com/2010/05/28/multiple-output-arguments/
| 
| The blogger is quite right that multiple output arguments are a
| problem. They require temporaries, and this makes for some slightly
| brittle code.
| 
| It's not difficult to implement a generalisation of the
| "2nd_output_of" function:
| 
|     function out = nthoutarg(fun, n, varargin)
|       outargs = cell (1,n);
|       [outargs{1:end-1}, out] = fun (varargin{:});
|     endfunction
| 
| Should this function be part of Octave? I'm all for prettifying the
| language as much as possible.
| 
| What do you think?

Because the value of nargout can change the behavior of a function,
you might need to specify the number of the argument you want and the
value of nargout to pass to the function separately.  For example,
when calling functions like svd.  With your definition of nthoutarg,

  nthoutarg (@svd, 2, rand (3, 4))

fails.  You need something like

  function out = nthoutarg (fun, n, nout, varargin)
    if (nargin > 2 && nout >= n)
      outargs = cell (1, nout);
      [outargs{:}] = fun (varargin{:});
      out = outargs{n};
    else
      print_usage ();
    endif
  endfunction

Then

  nthoutarg (@svd, 2, 3, rand (3, 4))

will work.

I know that the svd example is a bit contrived, because you can call
svd with a single output to get just the singular values as a vector,
but there are other instances where a function changes behavior based
on the value of nargout.  So it is not always just a simple matter of
throwing away the output values you don't want.

jwe


reply via email to

[Prev in Thread] Current Thread [Next in Thread]