1. 程式人生 > >Matlab非線性優化函數:fmincon();

Matlab非線性優化函數:fmincon();

令行 all clear 1.0 end 窗口 true atl con

技術分享圖片

技術分享圖片

%定義目標函數;
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

  

Matlab非線性優化函數:fmincon();