我需要优化以下功能:
f(x) = x^2 + y^3 + z^4
有约束:
x + y + z = 10
1.5 + xy - z <= 0
xy>= -10
和限制:
-10 <= x <= 10
-5 <= y <= 5
0 <= z <= inf
我需要使用这些选项:'LargeScale' = 'off', 'GradObj' =' on', 'GradConstr' = 'on',
我的代码看起来像:
options = optimset('LargeScale', 'off', 'GradObj','on','GradConstr','on');
A = [-1 0 0
1 0 0
0 -1 0
0 1 0
0 0 -1];
b = [-10 10 -5 5 0];
Aeq = [1 1 1];
beq = [10];
[x fval] = fmincon(@fun,[0 0 0],A, b, Aeq, beq,[],[],@constr, options);
function [y,g] = fun(x)
y = x(1).^2+x(2).^3+x(3).^4;
if nargout > 1
g = [2*x(1), 3*x(2).^2, 4*x(3).^3];
end
end
function [c,ceq, GC, GCeq] = constr(x)
c(1) = 1.5 + x(1)*x(2) - x(3);
c(2) = -10 - x(1)*x(2);
ceq = [];
if nargout > 2
GC = [x(2), -x(2);
x(1), -x(1);
0 , 0];
GCeq = [];
end
end
预期成果是:x = 10
y = -1
z = 0.05
你能给我一个建议吗?
应用于x(1)
和x(2)
的线性约束不正确。作用于x(1)
的两个约束,正如你给出的,将表示为:
x(1) <= 10
-x(1) <= -10
满足这些要求的唯一值是 x(1)=10
.将两个 RHS 值都设置为 10,您将对尝试实现的x(1)
强制执行边界。
为第一个非线性约束提供的梯度不正确,您缺少相对于x(3)
的梯度的 -1 值。
我在下面进行了修改。当我运行它时,我得到了[8.3084 0.0206 1.6710]
的最佳解决方案。我不相信你提供的预期结果是正确的,它们不满足x + y + z = 10
的平等约束
options = optimset('LargeScale', 'off', 'GradObj','on','GradConstr','on');
A = [-1 0 0
1 0 0
0 -1 0
0 1 0
0 0 -1];
b = [10 10 5 5 0];
Aeq = [1 1 1];
beq = [10];
[x fval] = fmincon(@fun,[0 0 0],A, b, Aeq, beq,[],[],@constr, options);
function [y,g] = fun(x)
y = x(1).^2+x(2).^3+x(3).^4;
if nargout > 1
g = [2*x(1), 3*x(2).^2, 4*x(3).^3];
end
end
function [c,ceq, GC, GCeq] = constr(x)
c(1) = 1.5 + x(1)*x(2) - x(3);
c(2) = -10 - x(1)*x(2);
ceq = [];
if nargout > 2
GC = [x(2), -x(2);
x(1), -x(1);
-1 , 0];
GCeq = [];
end