Milan
Milan

Reputation: 1740

Matlab functions handles and variable and unknown number of outputs

With an anonymous function, you can return any number of outputs. What I need is to be able to use functors (anonymous functions as arguments of other functions), while not knowing how many outputs I will get.

This is to avoid code duplication by injecting functions calls inside a while loop which is reused in many functions.

Example:

function y = foo( x )  
    y = x;
end

function [y1, y2] = goo( x1, x2 )  
    y1 = x1;
    y2 = x2;
end

function [ varargout ] = yolo( functor, varargin )  
    varargout = functor(varargin{:});    
end

I want to be able to call:

y = yolo(@foo, 2)
[y1, y2] = yolo(@goo, 3, 4);

Is there any way to achieve this ? Thanks

Upvotes: 2

Views: 298

Answers (1)

Suever
Suever

Reputation: 65430

It is not possible to get the number of outputs of an anonymous function (a function handle to an inline function) because the output is always varargout and therefore nargout is always going to return -1

myfunc = @(x, y) x + y;
nargout(myfunc)
%   -1

However, it looks like you don't have anonymous functions, but rather just function handles to normal functions that are defined in an .m file and have an explicit number of output arguments. In this case, you can combine nargout with {:} indexing to fill varargout with all of the output arguments.

function y = foo(x)
    y = x;
end

function [y1, y2] = goo(x1, x2)
    y1 = x1;
    y2 = x2;
end

function varargout = yolo(functor, varargin)
    [varargout{1:nargout(functor)}] = functor(varargin{:});
end

y = yolo(@foo, 2)
[y1, y2] = yolo(@goo, 3, 4)

Upvotes: 4

Related Questions