假设您要使用在MATLAB中定义的一系列函数,并且只需将这些函数的名称作为字符串变量即可。假设您已经创建了fun1
,fun2
... funN
、,并且还有一个向量为的字符串['fun1','fun2',...,'funN']
。如何自动调用每个函数而不必被迫一个个地写每个函数的名称?
使用str2func
。当然,如果已将函数定义为函数句柄(例如fun1 = @(x)x+x.^2+sqrt(x))
),则可以跳过下面的str2func步骤。
strList= {'sum','mean','max','min'};
funList = cellfun(@str2func,strList,'uniformOutput',false);
nFunctions = length(funList);
data = rand(10,1);
results = zeros(nFunctions,1)
for iFunction = 1:nFunctions
results(iFunction) = fulList{iFunction}(data);
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句