Omer Rosler
Omer Rosler

Reputation: 247

Create function with given number of input arguments

Here's the situation: I need to create a function that takes a function handle fun which is of CONSTANT input-length (that is nargin(fun)>=0), does some transformation on the inputs and then calls fun. Pseudo-Code:

function g = transformFun(fun)
n = nargin(fun);
g = @(v_1, ..., v_n) ...
%           ^ NOT REAL MATLAB - THE MAIN PROBLEM
    fun(someCalculationsWithSameSizeOfOutput(v_1,...v_n){:});
% CAN BE ACHIEVED WITH TEMPORARY CELL IN HELPER FUNCTION ^
end

Now the problem: the output function's handle (g = transformFun(concreteFun)) is then passed to other code that relies on the fact that the function is of constant length (assumes nargin(g)>=0), thus a variable-input-length function is unacceptable (the "easy" solution).

This transformation is called with many functions with every possible number of arguments (n is unbounded), so covering a finite number of possibilities is also not possible.

Is there a (simple?) way to achieve that?

[I've searched the internet for a few hours and could only come up with a nasty hack involving the deprecated inline function, which I couldn't make work; maybe I have the wrong terminology].

Upvotes: 4

Views: 122

Answers (1)

Suever
Suever

Reputation: 65430

So typically you could use varargin to handle this sort of thing, but since you need nargin(g) to return the actual number of inputs it's a little trickier.

You could use str2func to create the anonymous function as a string and then convert it to a function handle.

% Create a list or arguments: x1, x2, x3, x4, ...
args = sprintf('x%d,', 1:nargin(func));
args(end) = '';

% Place these arguments into a string which indicates the function call
str = sprintf('@(%s)fun(someCalculationsWithSameSizeOfOutput(%s))', args, args);

% Now create an anonymous function from this string
g = str2func(str);

Based on the attrocity above, it may be worth considering an alternative way of dealing with your function handles.

Upvotes: 4

Related Questions