这个函数在之前优化工具箱一文中已经介绍过,由于其应用广泛,所以这里通过实例单独整理一下其用法。
一、基本介绍
求解问题的标准型为
min F(X)
s.t
AX <= b
AeqX = beq
G(x) <= 0
Ceq(X) = 0
VLB <= X <= VUB
其中X为n维变元向量,G(x)与Ceq(X)均为非线性函数组成的向量,其它变量的含义与线性规划,二次规划中相同,用Matlab求解上述问题,基本步骤分为三步:
1. 首先建立M文件fun.m定义目标函数F(X):
function f = fun(X);
f = F(X)
2. 若约束条件中有非线性约束:G(x) <= 0 或 Ceq(x) = 0,则建立M文件nonlcon.m定义函数G(X)和Ceq(X);
function [G, Ceq] = nonlcon(X)
G = …
Ceq = …
3. 建立主程序,非线性规划求解的函数时fmincon,命令的基本格式如下:
fmincon函数用法” title=”[转载]Matlab
fmincon函数用法”>
注意:
(1)fmincon函数提供了大型优化算法和中型优化算法。默认时,若在fun函数中提供了梯度(options 参数的GradObj设置为’on’),并且只有上下界存在或只有等式约束,fmincon函数将选择大型算法,当既有等式约束又有梯度约束时,使用中型算法。
(2)fmincon函数的中型算法使用的是序列二次规划法。在每一步迭代中 求解二次规划子问题,并用BFGS法更新拉格朗日Hessian矩阵。
(3)fmincon函数可能会给出局部最优解,这与初值X0的选取有关。
二、实例
1. 第一种方法,直接设置边界
主要是指直接设置A,b等参数。
例1:min f = -x1 - 2*x2 + 1/2*x1^2 + 1/2 * x2^2
2*x1 + 3*x2 <= 6
x1 + 4*x2 <= 5
x1, x2 >= 0
function
x0
A
b
Aeq
beq
VLB
VUB
[x,
function
f |
2. 第二种方法,通过函数设置边界
例2: min f(x) = exp(x1) * (4*x1^2 + 2*x2^2 + 4*x1*x2 + 2*x2 + 1)
x1 + x2 = 0
1.5 + x1 * x2 - x1 - x2
<= 0
-x1*x2 - 10 <= 0
function
clc;
x0
A
Aeq
vlb
[x,
function
f
function
g
ceq |
3. 进阶用法,增加梯度以及传递参数
这里用无约束优化函数fminunc做示例,对于fmincon方法相同,只需将边界项设为空即可。
(1)定义目标函数
function
%COSTFUNCTION
%
%
%
%
m
%
J
grad
%
%
%
%
%
%
%
%
z
hx
J
for
end
%
end
|
(2)优化求极小值
%
options
%
%
[theta,
%
%
%
fprintf(’Cost
fprintf(’theta:
fprintf(’ |