Create a function with a given number of input arguments

Here's the situation: I need to create a function that takes a function descriptor funthat has an input length constant (i.e. nargin(fun)>=0), does some conversion 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 descriptor ( g = transformFun(concreteFun)) is then passed to another code that relies on the function to have a constant length (assumed nargin(g)>=0), so a variable input length function is unacceptable (an “easy” solution).

This conversion is called with many functions with any possible number of arguments ( nunlimited), so covering a finite number of possibilities is also impossible.

Is there a way (simple?) To achieve this?

[I searched the Internet for several hours and could only come up with a nasty hack using an outdated function inlinethat I could not do; I may have the wrong terminology].

+4
source share
1 answer

You can usually use vararginthese kinds of things to handle, but since you need nargin(g)to return the actual number of inputs, this is a bit more complicated.

You can use str2functo create an anonymous function as a string, and then convert it to a function descriptor.

% 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 above value, it might be worth considering an alternative way to work with your functions.

+4

Source: https://habr.com/ru/post/1662650/


All Articles