I would like to write a function like this:

function foo(goo,...)
  if( goo is a function of two variables )
    % do something
  else
    % do something else
  end
end

Is there any way I can get the number of variables of a inline function (or of an anonymous function?). To make it more clear:

f = inline('x + y')
g = inline('x')

I want to be able to distinguish that f is a function of two variables and g of 1 variable

有帮助吗?

解决方案


EDIT

After I answered this, a better strategy has been found: Just use nargin; see @k-messaoudi's answer.


For inline functions:

According to inline's help:

INLINE(EXPR) constructs an inline function object from the MATLAB expression contained in the string EXPR. The input arguments are automatically determined by searching EXPR for variable names (see SYMVAR).

Therefore: call symvar and see how many elements it returns:

>> f = inline('x + y');
>> g = inline('x');
>> numel(symvar(f))
ans =
     2
>> numel(symvar(g))
ans =
     1

For anonymous functions:

First use functions to get information about the anonymous function:

>> f = @(x,y,z) x+y+z;
>> info = functions(f)
info = 
     function: '@(x,y,z)x+y+z'
         type: 'anonymous'
         file: ''
    workspace: {[1x1 struct]}

Now, again use symvar on info.function:

>> numel(symvar(info.function))
ans =
     3

其他提示

define your variables : syms x1 x2 x3 .... xn;

define your function : f = inline(x1 + x2 + sin(x3) + ... );

number of input argument : n_arg = nargin(f)

number of output argument : n_arg = nargout(f)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top