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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! But why not i and j?
@sehlstrom - see the linked question regarding i and j.
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 ;-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.