我需要在Matlab中最大化方程式3x+y,并满足以下限制条件:
2x+y≤6, x+3y≤9,并且x,y≥0。
我很难想出一种方法将限制条件与原方程联系起来。我是Matlab的新手,很难弄清楚这一点。
提前感谢!
2x+y≤6, x+3y≤9,并且x,y≥0。
我很难想出一种方法将限制条件与原方程联系起来。我是Matlab的新手,很难弄清楚这一点。
提前感谢!
正如 @Franck 所提到的,通常可以使用 fmincon
来解决优化问题。然而,由于您的问题仅是一个线性规划问题,因此解决方案更简单(并保证最优):
f = -[3 1]; % Note the minus as we want maximization
A = [2 1; 1 3];
b = [6; 9];
LB = [0 0];
[X, FVAL] = linprog(f,A,b,[],[],LB)
将提供:
X =
3.0000
0.0000
FVAL =
-9.0000
function [] = maximize_stuff()
x0 = [2 2]; % fmincon starts at X0 and finds a minimum X
[x,fval] = fmincon('objfun',x0,[],[],[],[],[0;0],[Inf;Inf],'constraint');
fval = -fval; % Because we want to find the maximum, not the minimum
x
fval
end
objfun.m
function f=objfun(x)
f = 3*x(1) + x(2);
f = -f; % Because we want to find the maximum, not the minimum
end
constraint.m :
function [c,ceq]=constraint(x)
c1 = 2 * x(1) + x(2) - 6;
c2= x(1) + 3*x(2) - 9;
c = [c1;c2];
ceq = [];
end
它应该返回:
>> maximize_stuff
Local minimum found that satisfies the constraints.
Optimization completed because the objective function is non-decreasing in
feasible directions, to within the default value of the function tolerance,
and constraints are satisfied to within the default value of the constraint tolerance.
<stopping criteria details>
Active inequalities (to within options.TolCon = 1e-06):
lower upper ineqlin ineqnonlin
2 1
x =
3.0000 0
fval =
9.0000
fmincon
来解决线性问题似乎有点过度设计。 - Dennis Jaheruddin