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.m84 chars2 lines
fun: the objective function to be maximizedx0: the initial guess for the optimal value of xA, b: linear inequality constraintsAeq, beq: linear equality constraintslb, ub: lower and upper bounds on xnonlcon: nonlinear constraints (if any)options: further options for fminconHere'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.m520 chars24 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