Why my objective function is not evaluating the function for an initial value?

1 view (last 30 days)
I have a function like the following:
function y=testfuncopt(a,b,c)
Now I want to evaluate the function for an initial value x0:
objective =@(a,b,c) @testfuncopt;
disp(['Initial Objective: ' num2str(objective(a,b,c))])
The follwoing error happening:
Undefined function or variable 'a'.
Error in testopt1 (line 12)
disp(['Initial Objective: ' num2str(objective(a,b,c))])

Accepted Answer

Walter Roberson
Walter Roberson on 1 May 2019
You created a function handle that accepts three parameters with dummy names a b c. The code of the function handle says that when the function handle is invoked it should accept and ignore up to three parameters and should return a handle to testfuncopt but it should not itself invoke that function.
Then you attempt to invoke the function handle you just created passing in variables a b c from the current environment. That is failing because variable a does not exist.
If you had happened to have a b c in your environment then they would have been accepted by the function handle and ignored and the handle to testfuncopt would be returned. num2str would then fail trying to convert the function handle to string.
You talk about evaluating at an initial point and you have an x0 that looks like it might be an initial point for something but you are not passing it to your function handle and it is only one variable not three.
I think what you want is
objective = @(x) testfuncopt(x(1:2), x(3:4), x(5));
disp(['Initial Objective: ' num2str(objective(x0))])

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!