Home > Computer/Programming, Matlab > fmincon example with linear constraints

fmincon example with linear constraints

The following is a working example for ‘fmincon’. It tries to minimize the product (maximize the product if you account for the negative sign). There’re two linear constraints: the sum of the arguments should be equal to 10, and the sum of the first two arguments should be equal to the sum of the last two arguments.

mscr.m (the objective function)
function product = mscr(X)
product = -X(1)*X(2)^2*X(3)^3*X(4)^4;
disp(X);
disp(product);
return

main.m (script calling the objective function)
close all; clear all; clc
x0=[2.5;2.5;2.5;2.5];
Aeq=[1 1 1 1; 1 1 -1 -1];
beq=[10;0];
lb=[0;0;0;0];
ub=[10;10;10;10];
options=optimset('Algorithm','active-set');
[x,fval]=fmincon(@mscr,x0,[],[],Aeq,beq,lb,ub,{},options);

In conclusion here are a few tips:
– The function name, when passed to fmincon, can’t just be ‘mscr’ but it has to be ‘@mscr’ (I wonder why MATLAB doesn’t bother to specify that in bold in their help).
– If you want to specify ‘options’ without using non-linear constraint, use ‘{}’ as the empty space-holder. I had to find this out the hard way (i.e. by trial and error).
Remember that ‘fmincon’ is a minimizer. So if you want to maximize something, don’t forget the negative sign.

  1. No comments yet.
  1. August 20, 2012 at 12:55 am

Leave a comment