简体   繁体   中英

Matlab: Detect number of input arguments for function handle from outside of the function

I begin with a symbolic function of one variable, calculate the symbolic derivatives of orders 1 through N, and then convert those symbolic functions into function handles and store the function handles in a cell array. I then evaluate each function handle at the same input value using a loop. The problem I have is that it is possible for one of the derivatives to be a constant (with higher order derivatives being zero, of course). As I was trying to give each function handle an input, I face the "Too many input arguments" error. I would like to be able to check, in advance, whether the function handle is a constant so I can avoid the error, but I can't figure out how to do that.

In case a small working example is helpful, I provide the following

symVar = sym('symVar');
startFunc = symVar^4 + symVar^3 + symVar^2;
derivesCell = cell(5);
for J=1:5
    derivesCell(J) = {matlabFunction(diff(startFunc,symVar,J))};
end

cumSum = 0;
evalPoint = 2;
for J=1:5
    cumSum = cumSum + derivesCell{J}(evalPoint);
end

Execution produces "Error using symengine>@()2.4e1 Too many input arguments."

tl;dr: You can do this with nargin :

>> nargin(derivesCell{5})
ans =
     0

>> nargin(derivesCell{3})
ans =
     1


Explanation:
Most people are familiar with the use of nargin as a "special variable" inside the function, but it can be used outside the context of a function definition, as a function that takes a function_handle argument, returning the number of input arguments that function handle takes. From the documentation:

NARGIN(FUN) returns the number of declared inputs for the M-file function FUN. The number of arguments is negative if the function has a variable number of input arguments. FUN can be a function handle that maps to a specific function, or a string containing the name of that function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM