2

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

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, I was trying to look for a workaround using the number of outputs as an argument but it seems this will work, going to check this right now. I did not know I could use nargout as a function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.