MATLAB: How to pass additional parameters to the constraint and objective functions in the Optimization Toolbox functions in versions prior to MATLAB 7.0 (R14)

Optimization Toolbox

I would like to pass additional parameters to the nonlinear constraint function as well as objective function in my Optimization problem. I am using a MATLAB version prior to MATLAB 7.0 (R14) that did not support anonymous functions.

Best Answer

If you are using a version of MATLAB prior to MATLAB 7.0 (R14), which did not have the ability to create anonymous functions, you will need to pass the additional parameters into the objective and constraint functions as demonstrated in the example below. We are using FMINCON for demonstration purposes.
[x,fval] = fmincon(@fun,x0,A,b,Aeq,beq,lb,ub,@nonlcon,options,P1,P2,...)
FMINCON passes the problem-dependent parameters P1, P2, etc., directly to the functions "fun" , "nonlcon" and any function in the options structure.
In this case a nonlinear constraint function could be of this form:
function [c, ceq] = nonlcon(x,P1,P2)
c = x(1)*P1 - x(2)*P2
...
...
ceq = [];
Note that P1 and P2 are also available to "fun" whether you use it or not. You can try this simple example:
The objective function "fun" is :
function f = fun(x,p1,p2)
f = -x(1) * x(2) * x(3)*p1;
The nonlinear constraint function "nonlcon" is :
function [c, ceq] = nonlcon(x,p1,p2)
% Define two inequality constraints which use p1 and p2
c(1) = x(1)*p1 + 2*x(2)*x(1)*p2 + 2*x(3) - p2;
c(2) = x(1)*x(2)-100;
% Define the equality constraints
ceq(1) = x(2) -x(1)*x(2);
ceq(2) = x(2) - x(1)*x(3);
The call to FMINCON used to minimize this expression is:
x0 = [10; 10; 10];
p1 = 1;
p2 = 72;
lb = [0 0 0];
ub = [ 50 50 50];
options = optimset('Largescale','off','Display','iter');
[x, fval] = fmincon(@fun, x0, [], [], [], [], lb, ub, @nonlcon, options, p1, p2)
The ODE functions use the same convention for handling additional parameters as is described here. Additional information about the ODE solvers can be found in the related solution below.