How to add user defined function as constraint for optimization?

23 views (last 30 days)
Faruk Šehić
Faruk Šehić on 6 Jul 2022
Commented: Faruk Šehić on 6 Jul 2022
How to add user defined function as constraint for optimization? Example is given below. The problem that I know is a problem is that I am parsing a constraint to a function that sees that constraint as a variable, which it is not.
x = optimvar("x",3,3);
y = const1;
z = const2;
in loop:
return_val = my_fun(x(i,j),y)
prob.Constraints.Con1 = return_val >= z;
end loop
  4 Comments

Sign in to comment.

Accepted Answer

Matt J
Matt J on 6 Jul 2022
Edited: Matt J on 6 Jul 2022
Ultimately, you must use the solver-based approach, like Torsten says. However, if you download this,
you can still use problem-based tools to set-up the linear portion of the problem, e.g.,
x = optimvar("x",3,3,'Lower',0,'Upper',1);
Constraints.rowsum=sum(x,1)<0.5;
Constraints.colsum=sum(x,2)==1;
p=prob2matrices('Constraints',Constraints);
x=fmincon(@objective,x0,p.A,p.b,p.Aeq,p.beq,p.lb,p.ub, @(x) nonlcon(x,y,z))
function [c,ceq] = nonlcon(x,y,z)
c=z-my_fun(x,y); %my_fun must be differentiable in x
ceq=[];
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!