Main Content

如何使用所有类型的约束

此示例是一个非线性最小化问题,具有所有可能的约束类型。该示例不使用梯度。

此问题有五个变量,即 x(1)x(5)。目标函数是变量中的一个多项式。

f(x)=6x2x5+7x1x3+3x22.

目标函数在局部函数 myobj(x) 中,局部函数又嵌套在函数 fullexample 中。fullexample 的代码出现在此示例末尾

非线性约束同样是多项式表达式。

x1-0.2x2x571

0.9x3-x4267

3x22x5+3x12x3=20.875.

非线性约束在局部函数 myconstr(x) 中,该函数又嵌套在函数 fullexample 中。

该问题在 x3x5 上有边界。

0x320, x51.

此问题具有线性等式约束 x1=0.3x2,您可以将其写为 x1-0.3x2=0

该问题还有三个线性不等式约束:

0.1x5x4x40.5x50.9x5x3.

将边界和线性约束表示为矩阵和向量。创建这些数组的代码在 fullexample 函数中。如 fmincon输入参数部分中所述,lbub 向量表示约束

lb x ub.

矩阵 A 和向量 b 表示线性不等式约束

A*x b,

矩阵 Aeq 和向量 beq 表示线性等式约束

Aeq*x = b.

调用 fullexample 以求解在所有类型约束下的最小化问题。

[x,fval,exitflag] = fullexample
Local minimum found that satisfies the constraints.

Optimization completed because the objective function is non-decreasing in 
feasible directions, to within the value of the optimality tolerance,
and constraints are satisfied to within the value of the constraint tolerance.
x = 5×1

    0.6114
    2.0380
    1.3948
    0.1572
    1.5498

fval = 37.3806
exitflag = 1

退出标志值 1 指示 fmincon 收敛于一个满足所有约束的局部最小值。

以下代码创建 fullexample 函数,它包含嵌套函数 myobjmyconstr

function [x,fval,exitflag] = fullexample
x0 = [1; 4; 5; 2; 5];
lb = [-Inf; -Inf;  0; -Inf;   1];
ub = [ Inf;  Inf; 20; Inf; Inf];
Aeq = [1 -0.3 0 0 0];
beq = 0;
A = [0 0  0 -1  0.1
     0 0  0  1 -0.5
     0 0 -1  0  0.9];
b = [0; 0; 0];
opts = optimoptions(@fmincon,'Algorithm','sqp');
     
[x,fval,exitflag] = fmincon(@myobj,x0,A,b,Aeq,beq,lb,ub,...
                                  @myconstr,opts);

%---------------------------------------------------------
function f = myobj(x)

f = 6*x(2)*x(5) + 7*x(1)*x(3) + 3*x(2)^2;
end

%---------------------------------------------------------
function [c, ceq] = myconstr(x)

c = [x(1) - 0.2*x(2)*x(5) - 71
     0.9*x(3) - x(4)^2 - 67];
ceq = 3*x(2)^2*x(5) + 3*x(1)^2*x(3) - 20.875;
end
end

相关主题