how to maximize a function with constraints in matlab

One way to maximize a function with constraints in MATLAB is by using the fmincon function. fmincon solves an optimization problem subject to nonlinear constraints.

The general syntax of fmincon is:

main.m
[x,fval,exitflag,output,lambda] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options)
84 chars
2 lines
  • fun: the objective function to be maximized
  • x0: the initial guess for the optimal value of x
  • A, b: linear inequality constraints
  • Aeq, beq: linear equality constraints
  • lb, ub: lower and upper bounds on x
  • nonlcon: nonlinear constraints (if any)
  • options: further options for fmincon

Here's an example code snippet that shows how to use fmincon to maximize an objective function f = -x(1)*x(2) subject to the constraints x(1) + 2*x(2) <= 4, x(1) - x(2) >= 1, and x(1) >= 0:

main.m
% Define anonymous function for objective function
fun = @(x) -x(1)*x(2);

% Define initial guess for x and bounds on x
x0 = [1,1];
lb = [0,0];
ub = [];

% Define linear inequality and equality constraints
A = [1,2];
b = 4;
Aeq = [1,-1];
beq = -1;

% Define nonlinear constraints (none in this case)
nonlcon = [];

% Use fmincon to find optimal x and fval
[x,fval,exitflag,output,lambda] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon);

% Print results
disp(['Optimal x: ',num2str(x)])
disp(['Optimal f: ',num2str(-fval)])
520 chars
24 lines

Note that we defined the objective function fun using an anonymous function in this example, but it could also be defined as a regular function. Also, the exitflag, output, and lambda outputs of fmincon give information about the optimization process and can be useful for debugging.

gistlibby LogSnag