MATLAB: How to create constraints in fmincon

constraints in fmincon

Hi all,
I have a dataset with two variables x and y as follows:
10 0.006 11 0.017 12 0.026 …
50 0.003 51 0.002 52 0.001
I am trying to fit it with a nonlinear function with 4 parameters a, b, c, and d, of which c and d should be 10<c<52 and 10<d<52. The estimated y should be greater than 0. How can I create such constraints in fmincon? I was able to get the estimate using fminsearch. But many time, c and d and y do not meet the criterion.
lb and ub options in fminsearch are for y, not for parameters (right?) I am new with Matlab.
Thank you for warm support!
Rdu

Best Answer

This should be an optimization problem with nonlinear constraints, and the problem should be able to be solved using fmincon (See Documentation).
Before using fmincon, two functions need to be defined. One is the objective function, one is the nonlinear constraint function.
Let us denote the nonlinear function as foo(x,a,b,c,d), which is the mixture Beta distribution as you mentioned previously. Then, the objective function can be defined as
% Objective function
function err = myObj(p,x,y)
a = p(1);
b = p(2);
c = p(3);
d = p(4);
err = 0;
for i = 1:length(x)
err = (foo(x(i) , a, b, c, d) - y(i))^2;
end
end
% End the of the objective function
Save the above two functions as two separate MATLAB files of which the filenames are the same as the function names.
Now, the nonlinear constraint also needs to be defined. Since it is required that f(x,a,b,c,d)>=0 for all x, a way to defined the nonlinear constraint is
% Constraint function
function [nl,nl2] = nlcon(p,x)
a = p(1);
b = p(2);
c = p(3);
d = p(4);
nl = [];
for i = 1:length(x)
nl = [nl; -foo(x(i), a,b,c,d)];
end
nl2= [];
end
% End of the constraint function
Notice that I put a negative sign before foo. This is because fmincon requires the nonlinear constraint function to be smaller or equal to zero.
Now, in MATLAB command line or a script file, you can try the following steps
Step 1) Give values to x and y, such as
>> x =[10:52]; y = [0.006, 0.017, 0.026, ,..., 0.003, 0.002, 0.001]
Step 2) Specify the upper and lower bounds
>> lb = [10; 10; -inf; -inf]; % Assuming 10 is the lower bound for |a| and |b|
>> ub = [52; 52; inf; inf]; % Assuming 52 is the upper bound for |a| and |b|
Step 3) Specify the initial condition
>> p0 = [5;5;5;5]; % Give some initial guess for a,b,c,d
Step 4) Solve the optimization problem using fmincon
>> xx = fmincon(@(p)myObj(p,x,y),p0,[],[],[],[],lb,ub,@(p)nlcon(p,x))
Note that in the above code I use anonymous functions (See Documentation) to pass x and y. This is because fmincon requires the objective function and the constraint function to only contain the decision variable p as their arguments, while the functions I defined have (p,x,y) or (p,x) as the arguments. To ensure the functions satisfy the requirements of fmincon, I defined to anonymous functions which only depend on p.
-Yu