Anonymous function to class property method.
18 views (last 30 days)
I have a situation somewhat like the following mockup:
classdef (Abstract) absfoo
[f] = objfun(o, x)
[c, ceq] = confun(o, x)
classdef confoo < absfoo
function [f] = objfun(o, x)
f = sin(sum(x.^2));
function [c, ceq] = confun(o, x)
c(1) = cos(0.1+x(1).^2);
c(2) = x(1)+x(2);
ceq = ;
x0 = [0 1];
mf = confoo()
b = bar();
b.myfoo = mf;
Running runscr results in an error message similar to this:
Undefined function or variable 'o.myfoo.objfun'.
Error in fmincon (line 536)
If I add a wrapper method in bar, I can work around this error -- but I'd like to be able to do without the wrapper.
Edited to add commas to fmincon argument list and also empty lb, ub arguments per Steven's correction.
Steven Lord on 10 Jan 2020
Note: you shouldn't call your class bar as that already has a meaning in MATLAB.
fmincon(@(x) objfun(o.myfoo, x),x0,,,,,,,@(x) confun(o.myfoo, x))
The object o.myfoo isa confoo while x will be a double array. This means confoo is the dominant class. By the procedure listed here MATLAB will call the objfun method of the confoo class to call when fmincon tries to evaluate the anonymous objective function. The same holds for confun.
In addition to changing the objective and nonlinear constraint functions I had to add commas between the A, b, Aeq, and beq inputs as well as adding the lb and ub inputs as empty inputs.