我想写一个这样的函数:
function foo(goo,...)
if( goo is a function of two variables )
% do something
else
% do something else
end
end
有什么方法可以获取内联函数(或匿名函数)的变量数量吗?为了更清楚地说明:
f = inline('x + y')
g = inline('x')
我希望能够区分 f 是两个变量的函数,g 是 1 个变量的函数
最佳答案
编辑
在我回答这个问题后,找到了一个更好的策略:只需使用nargin
;请参阅@k-messaoudi's answer .
对于内联函数:
根据inline
的帮助:
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).
因此:调用 symvar
看看它返回了多少个元素:
>> f = inline('x + y');
>> g = inline('x');
>> numel(symvar(f))
ans =
2
>> numel(symvar(g))
ans =
1
对于匿名函数:
首先使用functions
获取匿名函数的信息:
>> f = @(x,y,z) x+y+z;
>> info = functions(f)
info =
function: '@(x,y,z)x+y+z'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
现在,再次在 info.function
上使用 symvar
:
>> numel(symvar(info.function))
ans =
3
关于matlab - 确定 Matlab 中内联函数的变量数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23564551/