I have a function called objective
in Matlab I evaluate by writing [f, df] = objective(x, {@fun1, @fun2, ..., @funN})
in a script. The functions fun1, fun2, ..., funN
have the format [f, df] = funN(x)
.
Inside objective
I want to, for each input in my cell array called fun
, evaluate the given functions using the Matlab built-in function feval
as:
function [f, df] = objective(x, fun)
f = 0;
df = 0;
for i = 1:length(fun)
fhandle = fun(i);
[fi, dfi] = feval(fhandle, x);
f = f + fi;
df = df + dfi;
end
end
I get the following error evaluating my objective
.
Error using feval
Argument must contain a string or function_handle.
I do not get how to come around this error.
You need to reference the elements of fun
using curly braces
fhandle = fun{i};
PS
It is better not to use i
and j
as variable names in Matlab
Alternatively, a solution using cellfun
.