I need to maximize the equation 3x+y in matlab with the following constraints:
2x+y<=6, x+3y<=9, and x,y>=0
I am having a really hard time figuring out
Create the following files and run maximize_stuff:
maximize_stuff.m:
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
It should return:
>> 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.
Active inequalities (to within options.TolCon = 1e-06):
lower upper ineqlin ineqnonlin
2 1
x =
3.0000 0
fval =
9.0000
You can verify the results http://www.wolframalpha.com/input/?i=2x%2By%3C%3D6%3B+x%2B3y%3C%3D9%3B+x%3E%3D0%3By%3E%3D0%3B :
A very good tutorial: http://www.math.colostate.edu/~gerhard/classes/331/lab/fmincon.html
fmincon is called as follows:
with linear inequality constraints Ax£b only (as in linprog): [x,fval]=fmincon('objfun',x0,A,b)
with linear inequality constraints and linear equality constraints Aeq·x=beq only: [x,fval]=fmincon('objfun',x0,A,b,Aeq,beq)
with linear inequality and equality constraints, and in addition a lower bound of the form x³lb only: [x,fval]=fmincon('objfun',x0,A,b,Aeq,beq,lb) If only a subset of the variables has a lower bound, the components of lb corresponding to variables without lower bound are -Inf. For example, if the variables are (x,y), and x³1 but y has no lower bound, then lb=[1;-Inf].
with linear inequality and equality constraints and lower as well as an upper bound of the form x£ub only: [x,fval]=fmincon('objfun',x0,A,b,Aeq,beq,lb,ub) If only a subset of the variables has an upper bound, the components of ub corresponding to variables without upper bound are Inf. For example, if the variables are (x,y) and x£1 but y has no lower bound, then lb=[1;Inf].
with linear inequality and equality constraints, lower and upper bounds, and nonlinear inequality and equality constraints: [x,fval]=fmincon('objfun',x0,A,b,Aeq,beq,lb,ub,'constraint') The last input argument in this call is the name of a function file (denoted constraint in these notes and saved as constraint.m in the working directory), in which the nonlinear constraints are coded.