# How do I pass additional parameters to the constraint and objective functions in the Optimization Toolbox functions?

239 views (last 30 days)
I would like to parameterize my objective function and constraint function in my optimization problem using the Optimization toolbox. Typically this is needed when I want to use parameters and design variables together in an optimization problem.

MathWorks Support Team on 22 Jan 2010
You can pass additional parameters to the nonlinear constraint function as well as objective function using anonymous functions, inline functions, or function files for the objective and constraint functions. An example of this is given below.
Anonymous functions allow you to parameterize your objective and constraint functions.
The objective function "fun" can be defined in a function file:
function f = fun(x,p1)
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 parameters 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 where the additional parameter P1 is passed to the objective function, and parameters P1 and P2 to the constraint function 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(@(x)fun(x,p1), x0, [], [], [], [], lb, ub, @(x)nonlcon(x,p1,p2), options)
For simple objective functions, it is possible to define the objective function in the call to FMINCON, and have no objective function file:
[x, fval] = fmincon(@(x)-x(1)*x(2)*x(3)*p1, x0, [], [], [], [], lb, ub, @(x)nonlcon(x,p1,p2), options)
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.
Fausto Melendez on 21 Jun 2021
how do you check the random value the parameters p1,p2 got?

Abdulazizk on 5 Jan 2018
I have problem like. both x and p need to be variable values. I try like this.
function [c, ceq] = nonlcon(x,p)
% Define two inequality constraints which use parameters P1 and P2
c(1) = x(1)*p(1) + 2*x(2)*x(1)*p(2) + 2*x(3) - p(2);
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);
end
Then apply
x0 = [10; 10; 10];
p0 = [1;72];
lb = [];
ub = [];
options = optimset('Largescale','off','Display','iter');
[x,p, fval] = fmincon(@(x,p)-x(1)*x(2)*x(3)*p(1), x0, [], [], [], [], lb, ub, @(x,p)nonlcon(x,p),
options)
end

MathWorks Support

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!