how to minimize a function with linear constraints in matlab

To minimize a function with linear constraints in Matlab, you can use the built-in function fmincon. This function finds the minimum of a function subject to constraints on the variables, where the constraints are linear expressions.

The general syntax of fmincon is:

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

where:

  • fun: is a function handle to the objective function you want to minimize
  • x0: is a vector of initial guess for the optimization variables
  • A,b: define the inequality constraints A*x <= b
  • Aeq,beq: define the equality constraints Aeq*x = beq
  • lb,ub: define the lower and upper bounds for each variable

Here is an example code that illustrates how to use fmincon to minimize a quadratic function with linear constraints:

main.m
% Objective function
fun = @(x) (x(1)-2)^2 + (x(2)-1)^2;

% Initial guess
x0 = [0,0];

% Inequality constraints: Ax <= b
A = [1,1;
    -1,2;
    2,1];
b = [2;-1;3];

% Equality constraints: Aeq x = beq
Aeq = [];
beq = [];

% Lower and upper bounds for each variable
lb = [-1,-1];
ub = [3,2];

% Call fmincon
[x,fval,exitflag,output] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub);

% Print results
disp(['Minimum found at x = (',num2str(x(1)),',',num2str(x(2)),')']);
disp(['Minimum value is: ',num2str(fval)]);
501 chars
27 lines

This code defines an objective function (x(1)-2)^2 + (x(2)-1)^2 and finds its minimum subject to 3 linear constraints and bounds on the variables. The output x contains the optimal solution, fval the optimal function value, exitflag the exit status and output additional information about the optimization process.

gistlibby LogSnag