Reputation: 203
Suppose you want to use a sequence of functions defined in MATLAB, and you just have the name of those functions as string variables. Let say you have already created fun1
, fun2
, ...,funN
, and you also have a vector of strings as ['fun1','fun2',...,'funN']
. How to call each function automatically without being forced to write name of each function one by one?
Upvotes: 1
Views: 285
Reputation: 74940
Use str2func
. Of course, if the functions have been defined as function handles (e.g. fun1 = @(x)x+x.^2+sqrt(x))
), you can skip the str2func step below.
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
Upvotes: 6