Matlab非线性优化函数:fmincon();

%定义目标函数;
function f = myfun(x)
f = x(1)^2 + x(2)^2 + 8;
end


%非线性约束; function [c, ceq] = nonlia(x) c = -x(1)^2 + x(2); %不等式约束; ceq = -x(1) - x(2)^2 + 2; %等式约束; end %在命令窗口输入: A = []; b = []; Aeq=[]; beq=[]; lb = [0; 0]; ub = []; x0 = [0; 0]; [x,fval,exitflag,output,lambda,grad,hessian] = fmincon('myfun',x0,A,b,Aeq,beq,lb,ub,'nonlia'); 得:x = 1.0000 1.0000 fval = 10.0000

 

%目标函数;
function f = myfun(x)
f = -x(1) - 2*x(2) +0.5*x(1)^2 + 0.5*x(2)^2;
end


%非线性约束;
function [c, ceq] = nonlia(x)
c = 2*x(1) + 3*x(2)^2 - 6;       %不等式约束;
ceq = []; %等式约束;
end


%在命令窗口输入:
clc;
clear all;
A = [2 3; 1 4];  %线性不等式系数;
b = [6;5];       
Aeq = [];       
beq = [];
lb = [0; 0];
ub = [];
x0 = [0; 0];
[x,fval,exitflag,output,lambda,grad,hessian] = fmincon('myfun',x0,A,b,Aeq,beq,lb,ub,'nonlia');

得:x =

    0.7647
    1.0588

>> fval

fval =

   -2.0294

  

注意这里是求最大值,目标函数需要取反;

%目标函数;
function f = myfun(x)
f = -(log(x(1)) + log(x(2)));
end


%非线性约束;
function [c, ceq] = nonlia(x)
c = [];       %不等式约束;
ceq = [];     %等式约束;
end

%在命令行输入:
clc;
clear all;
A = [1 -1];
b = 0;
Aeq= [1 2];
beq = 5;

lb = [0; 0];
ub = [];
x0 = [0; 0];
[x,fval,exitflag,output,lambda,grad,hessian] = fmincon('myfun',x0,A,b,Aeq,beq,lb,ub,'nonlia');

得:x =

    1.6667
    1.6667

>> fval

fval =

   -1.0217

  

%定义目标函数;
function f = myfun(x)
f = sqrt(x(2));
end



%非线性约束;
function [c, ceq] = nonlia(x)
c = [8*x(1)^3-x(2);(1-x(1))^3-x(2)];  %多个不等式约束情况; 
ceq =[]; %等式约束;
end



%在窗口输入如下命令
A = [];
b = [];
Aeq = [];
beq = [];
lb = [0,0];
ub = [];
x0 = [1.234; 5.678];
[x,fval,exitflag,output,lambda,grad,hessian] = fmincon('myfun',x0,A,b,[],[],lb,[],'nonlia');



得:
x =

    0.3333
    0.2963

>> fval

fval =

    0.5443

  

posted on 2018-11-08 20:50  忠诚的卫士  阅读(1816)  评论(0编辑  收藏  举报

导航