how to minimize a function with constraints in matlab

To minimize a function subject to constraints in MATLAB, you can use the fmincon function in the Optimization Toolbox. This function finds the minimum of a constrained nonlinear multivariable function. The general syntax is:

main.m
[x, fval] = fmincon(fun, x0, A, b, Aeq, beq, lb, ub, nonlcon)
62 chars
2 lines

where fun is the objective function to minimize, x0 is the initial guess for the variables, A and b are matrices defining linear inequalities A*x <= b, Aeq and beq are matrices defining linear equalities Aeq*x = beq, lb and ub are the lower and upper bounds of the variables, and nonlcon is a function handle defining the nonlinear constraint nonlcon(x) <= 0.

Here is an example of how to use fmincon to minimize the Rosenbrock function subject to linear and nonlinear constraints:

main.m
% define the objective function
fun = @(x) 100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;

% define the linear inequality constraints A*x <= b
A = [1 1]; % x1 + x2 <= 1
b = 1;

% define the linear equality constraints Aeq*x = beq
Aeq = [];
beq = [];

% define the lower and upper bounds of x
lb = [-10; -10]; % lower bounds for x1 and x2
ub = [10; 10];   % upper bounds for x1 and x2

% define the nonlinear constraint nonlcon(x) <= 0
nonlcon = @(x) x(2) - x(1)^2;

% define the initial guess
x0 = [0; 0];

% optimize the function with fmincon
[x, fval] = fmincon(fun, x0, A, b, Aeq, beq, lb, ub, nonlcon)

% output the results
fprintf('x = [%f; %f]\n', x(1), x(2));
fprintf('fval = %f\n', fval);
688 chars
28 lines

In this example, the objective function is the Rosenbrock function, which is subject to the linear inequality constraint x1 + x2 <= 1 and the nonlinear inequality constraint x2 - x1^2 <= 0. The initial guess for x is [0;0]. fmincon returns the optimal value for x in the variable x and the minimum value of the function in the variable fval.

gistlibby LogSnag