0

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.

sehlstrom
  • 389
  • 2
  • 7
  • 18

2 Answers2

3

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.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
2

A more elegant approach using cellfun

function [f df] = objective( x, fun )
[f, df] = cellfun( @(f) f(x), fun );
f = sum(f);
df = sum(df);

Note the kinky use of cellfun - the cellarray is the fun rather than the data ;-)

Shai
  • 111,146
  • 38
  • 238
  • 371