Non linear constraint for optimization

I have a code which aims to optimize a function with linear and non linear constraint. However, it doesn't work due to the non linear constraint x^2 <= y. I wrote where the problem is
% definition of x and y
x=-10:0.1:10;
y=-0.4:0.1:10;
% define a grid (x,y)
[xx,yy]=meshgrid(x,y);
%
% Evaluation of f(x,y) on this grid
%
zz = f(xx,yy); %%%%TO DEFINE
% 3D surface
figure(1), surf(x,y,zz), colormap hsv
camlight;
shading interp
lighting gouraud
view(3)
% Visualize the level sets:
figure(2),
contour(x,y,zz,[0:1:10]);
%or contour3(x,y,zz,[0:1:10]);
%Quasi Newton
fun = @(x)(x(2)-cos(2*x(1))-((x(1).^2)/10)).^2 +exp((x(1).^2 + x(2).^2)/100);
x0 = [1, 1]; % initial conditions
A=[-1,-1]; % -x - y <= b
b=[-4]; % If several linear constraints, put a vector
options = optimset('Display','iter');
options2 = optimoptions('lsqnonlin','Display','iter');
%options2 = optimoptions('lsqnonlin','Display','iter','SpecifyObjectiveGradient',true);
[qN_x, qN_fval] = fmincon(fun, x0, A, b,[],[],[],[],[], options);
% With a new non linear constraint
% THE PROBLEM IS HERE !!!
[qN_x_nonlin, qN_fvalnonlin] = fmincon(fun,x0,A,b,[],[],[],[], @mycon, options);
%Least Square
[ls_x, ls_resnorm] = lsqlin(fun, x0, [],[], options2);
%Simplex
[NMs_x, NMs_fval] = fminsearch(fun, x0, options);
function z=f(x,y)
z=(y-cos(2*x)-((x.^2)/10)).^2 +exp((x.^2 + y.^2)/100);
end
% THE PROBLEM IS HERE !!!!
function [c,ceq] = mycon(x)
c= x(2).^2 - x(3);
ceq=0;
end
Thanks

 Accepted Answer

Torsten
Torsten on 8 Nov 2018
Edited: Torsten on 8 Nov 2018
function [c,ceq] = mycon(x)
c= x(1)^2 - x(2);
ceq = [];
end

More Answers (1)

However, I have an another error which I don't understand now:
Error using lsqlin (line 139) LSQLIN requires the following inputs to be of data type double: 'C','Aeq'.
Error in td1q6 (line 41) [ls_x, ls_resnorm] = lsqlin(fun, x0, [],[], options2);
I didn't get this error before.

4 Comments

Look at the documentation on how to call lsqlin.
Further, it's not appropriate for your problem because you have a nonlinear objective function and a nonlinear constraint.
Yes because for the least square function, I only have a linear constraint ... So I used the linear least square optimization function.
But you pass "fun" as first argument which is a nonlinear function, not a constant matrix as required.
I'm so sorry, I now understand what you mean. Thank you !

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!