%定义目标函数; 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
原文地址:https://www.cnblogs.com/GuanghuiLiu/p/9931946.html
时间: 2024-11-10 01:10:31