# Matlab fmincon for a problem with many nonlinear constraints

Using Matlab to solve a problem which has linear objective function and many nonlinear constraints, I am trying to generate the inequality nonlinear constraints by a function and pass it to fmincon solver via nonlcon option. My question is if there are no equality nonlinear constraints in the model what should the constraints generator pass to fmincon? I tried the following:

function [c, ceq] = consgenerator(x)

c = @(x) *[some constraints]*;

ceq = [];

end


In another attempt, I tried:

ceq = @(x) [];


I got errors in both trials and couldn’t find an example of passing many nonlinear inequality constraints into fmincon.

The problem might be @(x) in the first line of the function. Adding this creates an anonymous function, while MATLAB simply expects a numerical vector as output. Removing @(x) should resolve the issue. Using ceq = [] should not give any problems.

• Thanks Kevin, I will definitely give a try... – Oguz Toragay Sep 5 '19 at 4:05

Following Kevin Dalmeijer's answer (Accepted), I found the following approach to solve the problem that I had. (composing this answer for future similar questions):

The general form of Fmincon function (minimizing constrained nonlinear multivariable function) in Matlab optimization toolbox is as follow:

Option 1: fmincon(ObjFun,x0,A,b,Aeq,beq,lb,ub,@nonlcon,options); or
Option 2: fmincon(ObjFun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options);


in which nonlcon (used to add the nonlinear constraints to the model) can be a function name or a function handle (by putting @ before function's name). Two mentioned expressions have a very slight difference in their implementation.

• For the first case, as Kevin mentioned you can define a function with the same name and generate all the nonlinear constraints (including Equality and Inequality) and return [c,ceq] to Fmincon as the output of the defined nonlcon function. In this option, c and ceq can be two vectors of residual.
• In the second option, function handle should be either defined outside of definition of Fmincon or defined inside the nonlcon function.

Explanation of all the other variables in fmincon can be found here.

I tried the combination of two approaches which caused the error in my code.

You can specify many nonlinear constraints and objectives without having to define functions with the problem-based modeling approach starting with MATLAB R2019a. "Many" are those that are polynomial or rational expressions. For example:

p = optimproblem;
x = optimvar("x","LowerBound",0);
y = optimvar("y","LowerBound",0);
p.Objective = x + y;
p.ObjectiveSense = "min";
p.Constraints.c1 = x^2 - y^2 >= 10;
initPt.x = 4;
initPt.y = 4;
sol = solve(p,initPt)


For other expressions, you will still need to write functions. Details here.