Help using a class method as an objective function for fmincon does not work

I want to use fmincon inside a class object, using a class method . When I try it I find that fmincon cannot see the function, even though the function is defined appropriately at the time of the call to fmincon. I wrote a test class to illustrate the problem which is attached.
test = testfmincon
min(test)

 채택된 답변

func = @(x)objectiveFunction(obj, x)
x0 = [1,1,1];
[x,fval,exitflag,output] = fmincon(@func,x0,A,b,Aeq,beq,[],[],nonlcon,options);
The func variable is an anonymous function. Since you're passing the object into objectiveFunction (which is a method of the class) this will call the method. You don't need the extra @ in the fmincon call, pass func not @func as the first input.
You did not include the gaussian function in your code but I replaced it with a call to randn that I suspect is similar.
You're using data (which is a property of your object) inside objectiveFunction but I think the second reference to it on the first line should call makedata instead. I'd recommend not using the same name for a local variable inside the method and a property of the object as it can lead human beings to be confused about which you're referring to.
Finally, your min method (which I might call minimize to avoid confusion with the min function in MATLAB) says it returns a variable outputArg but never defines that variable. So if you called the method with 0 outputs it would work but calling it with an output would error.

추가 답변 (0개)

제품

릴리스

R2020a

질문:

2021년 8월 16일

댓글:

2021년 8월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by