[Top][All Lists]

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

Re: Handling variable number of output arguments in multi-level function

From: Juan Pablo Carbajal
Subject: Re: Handling variable number of output arguments in multi-level function calls
Date: Fri, 12 Dec 2014 13:41:05 +0100

On Fri, Dec 12, 2014 at 1:21 PM, Philip Nienhuis
<address@hidden> wrote:
> Jose wrote
>> Dear community.
>> I often face the situation in which a function (say f1) calls another
>> function internally (say f2) whose number of outputs depends on the
>> number of outputs requested from the upper calling function f1.
>> Something like this
>> --->
>> function [o1,o2]=f1(varargin)
>>    ...
>>    if nargout==1
>>      [o1]=f2(varargin{:});
>>    elseif nargout==2
>>      [o1,o2]=f2(varargin{:});
>>    endif
>>    ...
>> endfunction
>> <---
>> This example shows how I am handling the problem of calling f2 with the
>> right number of output arguments. I suspect that this is something that
>> other users also face often, and I also suspect that there might be a
>> better way to handle this (one can imagine easily how the code gets
>> cluttered in case there are many output arguments).
>> Does somebody know a more elegant (and perhaps more efficient?) way to
>> handle this?
> "code gets cluttered" - that depends on what one calls "cluttered". That's a
> question of coding discipline.
> There are the standard ways to keep code readable and maintainable as much
> as possible:
> - code layout
> - subfunctions
> - to-the-point comments
> - plus more sophisticated stuff (doxygen, ...)
> AFAIK nargout is the most suitable way to deal with output depending on the
> number of requested output args.
> There are other ways, like
> [~, ~, outarg3, ~, outarg5] = foobar (varargin)
> that uses only output arguments #3 and#5 and skips the rest. But then the
> selection of which outargs to use is made by the caller, not the called
> function (foobar). Then foobar() will always compute all output args,
> whether requested or not , which depending on the case at hand may be a
> negligible or significant waste of CPU cycles.
> Another way is to return outputs (don't forget to at least initialize all)
> depending on the number of input args to foobar().
> I think that's about all the choice there is.
> Philip
> --
> View this message in context: 
> Sent from the Octave - General mailing list archive at
> _______________________________________________
> Help-octave mailing list
> address@hidden

If you use varargout in your f1 function, then you could do

OUT = nthargout (1:nargout, @f2, varargin{:});

and then distribute the cell OUT in the outputs of f1. I think you
will have to have a special check for the case nargout=1.

reply via email to

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