MPC Ug Removed
MPC Ug Removed
Nonlinear MPC
As in traditional linear MPC, nonlinear MPC calculates control actions at each control interval using a
combination of model-based prediction and constrained optimization. The key differences are:
• Simulate closed-loop control of nonlinear plants under nonlinear costs and constraints.
• Plan optimal trajectories by solving an open-loop constrained nonlinear optimization problem.
By default, nonlinear MPC controllers solve a nonlinear programming problem using the fmincon
function with the SQP algorithm, which requires Optimization Toolbox™ software. If you do not have
Optimization Toolbox software, you can specify your own custom nonlinear solver. For more
information on configuring the fmincon solver and specifying a custom solver, see “Configure
Optimization Solver for Nonlinear MPC” on page 9-30. For more information about using the
FORCESPRO NLP solver with nonlinear MPC controllers, see “Implement MPC Controllers Using
Embotech FORCESPRO Solvers” on page 10-73.
Note The MPC Designer app does not support the design of nonlinear MPC controllers.
• State and output functions that define your prediction model. For more information, see “Specify
Prediction Model for Nonlinear MPC” on page 9-5.
• A custom cost function that can replace or augment the standard MPC cost function. For more
information, see “Specify Cost Function for Nonlinear MPC” on page 9-13.
• Standard bounds on inputs, outputs, and states.
• Additional custom equality and inequality constraints, which can include linear and nonlinear
combinations of inputs, outputs, and states. For more information, see “Specify Constraints for
Generic Nonlinear MPC” on page 9-20.
• Passivity inequality constraints, which can include linear and nonlinear combinations of inputs and
states. For more information, see “Specify Constraints for Generic Nonlinear MPC” on page 9-20
and the Passivity property of the nlmpc object. For examples about passivity, see “Control
Quadruple-Tank Using Passivity-Based Nonlinear MPC” on page 9-182 and “Control Robot
Manipulator Using Passivity-Based Nonlinear MPC” on page 9-187.
9-2
Nonlinear MPC
For a multistage MPC controller, each stage has its own decision variables and parameters, as well as
its own nonlinear cost and constraints. More importantly, cost and constraint functions at a specific
stage are functions only of the decision variables and parameters at that stage. Other than make it
easier to write Jacobian functions, this feature allows for a much more efficient data structure, which
in turn significantly reduces computation times compared to the same problem solved using a generic
NLMPC controller. The fact that slack variables are stage-based allows for more design flexibility, and
disabling the use of manipulated variable rates as decision variables yields an even leaner problem
formulation.
For these reason, if your nonlinear MPC problem has cost and constraint functions that do not involve
cross-stage terms, and if you do not need to enforce passivity, use multistage nonlinear MPC
controller in your design.
To implement a multistage nonlinear MPC controller, first create an nlmpcMultistage object, and
then specify:
• State functions that define your prediction model. For discrete-time models, make sure
Model.IsContinuousTime is set to false.
• Cost and constraint functions at the desired stages. You must specify the cost function for at least
one stage.
• Hard upper and lower bounds on states, manipulated variables, and manipulated variable rates, if
needed.
Code generation from a nonlinear multistage controller is supported in both MATLAB (using
mpcmoveCodeGeneration) and Simulink.
For examples on how to create and use a multistage MPC controller, see “Create and Simulate
Multistage Nonlinear MPC Controller”, “Simulate Multistage Nonlinear MPC Controller Using Initial
9-3
9 Nonlinear MPC
Guesses”, and “Truck and Trailer Automatic Parking Using Multistage Nonlinear MPC” on page 9-
158.
See Also
Functions
generateJacobianFunction | validateFcns | nlmpcmove
Objects
nlmpc | nlmpcMultistage | nlmpcmoveopt
Blocks
Nonlinear MPC Controller | Multistage Nonlinear MPC Controller
Related Examples
• “Trajectory Optimization and Control of Flying Robot Using Nonlinear MPC” on page 9-54
• “Control of Quadrotor Using Nonlinear Model Predictive Control” on page 9-141
• “Nonlinear Model Predictive Control of an Exothermic Chemical Reactor” on page 9-90
• “Swing-Up Control of a Pendulum Using Nonlinear Model Predictive Control” on page 9-76
• “Control Quadruple-Tank Using Passivity-Based Nonlinear MPC” on page 9-182
• “Plan and Execute Task- and Joint-Space Trajectories Using KINOVA Gen3 Manipulator”
(Robotics System Toolbox)
• “Landing a Vehicle Using Multistage Nonlinear MPC” on page 9-172
• “Truck and Trailer Automatic Parking Using Multistage Nonlinear MPC” on page 9-158
More About
• “Economic MPC” on page 9-148
• “Specify Prediction Model for Nonlinear MPC” on page 9-5
• “Specify Cost Function for Nonlinear MPC” on page 9-13
• “Specify Constraints for Generic Nonlinear MPC” on page 9-20
• “What is Model Predictive Control?”
9-4
Specify Prediction Model for Nonlinear MPC
• State function — Predicts how the plant states evolve over time
• Output function — Calculates plant outputs in terms of state and input variables
Before simulating your controller, it is best practice to validate your custom functions, including the
state function, output function, and their Jacobians using the validateFcns command.
For an example on how to use a neural state-space model identified from data as a prediction model
for a multistage nonlinear MPC problem, see “Control House Heating System Using Nonlinear Model
Predictive Control With Neural State-Space Prediction Model” on page 9-192.
State Function
You can specify either a continuous-time or a discrete-time state function. For a:
• Continuous-time prediction model, the state function is the state derivative function.
dx/dt = f x, u
• Discrete-time prediction model, the state function is the state update function.
x k + 1 = f x k ,u k
Since a nonlinear MPC controller is a discrete-time controller, if your state function is continuous-
time, the controller automatically discretizes the model using the implicit trapezoidal rule. This
method can handle moderately stiff models, and its prediction accuracy depends on the controller
sample time; that is, a large sample time can potentially lead to inaccurate prediction.
If the default discretization method does not provide satisfactory prediction for your application, you
can specify your own discrete-time prediction model that uses a different method. To do so, you can
integrate a continuous-time state function from the given initial condition, xk, to the next state, xk+1.
When doing so numerically, avoid approaches that require iterations, such as some variable-step-size
methods, because these methods introduce numerical noise that degrades solver performance. An
explicit multistep Euler method with sufficiently small step size is often the best method to try first.
For an example, see “Swing-Up Control of a Pendulum Using Nonlinear Model Predictive Control” on
page 9-76.
You can specify your state function in one of the following ways.
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Model.StateFcn = "myStateFunction";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path
Model.StateFcn = @myStateFunction;
9-5
9 Nonlinear MPC
• Anonymous function
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
function z = myStateFunction(x,u)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:
function z = myStateFunction(x,u,params)
This table describes the inputs and outputs of this function, where:
As an example of a state function, consider the continuous-time model with the following state
equations:
9-6
Specify Prediction Model for Nonlinear MPC
ẋ 1 = x4
ẋ 2 = x5
ẋ 3 = x6
ẋ 4 = u1 − u2 + u3 − u4 cos x3
ẋ 5 = u1 − u2 + u3 − u4 sin x3
ẋ 6 = 0.2 u1 − u2 − u3 + u4
To improve computational efficiency, it is best practice to specify an analytical Jacobian for your state
function. If you do not specify a Jacobian, the controller computes the Jacobian using numerical
perturbation. To specify a Jacobian for your state function, set the Jacobian.StateFcn property of
the controller to one of the following.
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Jacobian.StateFcn = "myStateJacobian";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path
Jacobian.StateFcn = @myStateJacobian;
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
Your state Jacobian function must have one of the following signatures.
9-7
9 Nonlinear MPC
The input arguments of the state Jacobian function are the same as the inputs of the state function.
This table describes the outputs of the Jacobian function, where:
Argument Description
A Jacobian of the state function output, z, with respect to x, returned as an Nx-by-
Nx array, where A i, j = ∂z i / ∂x j .
Bmv Jacobian of the state function output with respect to the manipulated variables,
specified as an Nx-by-Nmv array, where Bmv i, j = ∂z i / ∂u MV j and MV(j) is
the jth MV index in the Dimensions.MVIndex controller property. Bmv
contains the gradients with respect to only the manipulated variables in u, since
the measured and unmeasured disturbances are not decision variables.
Consider again, the state function with the following state equations:
ẋ 1 = x4
ẋ 2 = x5
ẋ 3 = x6
ẋ 4 = u1 − u2 + u3 − u4 cos x3
ẋ 5 = u1 − u2 + u3 − u4 sin x3
ẋ 6 = 0.2 u1 − u2 − u3 + u4
To find the Jacobians, compute the partial derivatives of the state equations with respect to the states
and manipulated variables, assuming that all four inputs are manipulated variables.
A = zeros(6,6);
A(1,4) = 1;
A(2,5) = 1;
A(3,6) = 1;
A(4,3) = -(u(1) - u(2) + u(3) - u(4))*sin(x(3));
A(5,3) = (u(1) - u(2) + u(3) - u(4))*cos(x(3));
B = zeros(6,4);
B(4,:) = cos(x(3))*[1 -1 1 -1];
B(5,:) = sin(x(3))*[1 -1 1 -1];
B(6,:) = 0.2*[1 -1 -1 1];
Note For multistage nonlinear MPC, you can automatically generate a state Jacobian function using
generateJacobianFunction.
Output Function
The output function of your prediction model relates the states and inputs at the current control
interval to the outputs. If the number of states and outputs of the prediction model are the same, you
can omit OutputFcn, which implies that all states are measurable; that is, each output corresponds
to one state.
9-8
Specify Prediction Model for Nonlinear MPC
Note OutputFcn cannot have direct feedthrough from any manipulated variable to any output at
any time; in other words, nonlinear MPC always assumes Dmv = 0.
You can specify your output function in one of the following ways.
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Model.OutputFcn = "myOutputFunction";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path
Model.OutputFcn = @myOutputFunction;
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
function y = myOutputFunction(x,u)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:
function y = myOutputFunction(x,u,params)
This table describes the inputs and outputs of this function, where:
9-9
9 Nonlinear MPC
As an example of an output function, consider the following output equations. Recall, that your output
function cannot have direct feedthrough from any manipulated variable to any output at any time.
y1 = x1
y2 = x2 + 0.2x3
y3 = x3 ⋅ x4
To improve computational efficiency, it is best practice to specify an analytical Jacobian for your
output function. If you do not specify a Jacobian, the controller computes the Jacobian using
numerical perturbation. To specify a Jacobian for your output function, set the
Jacobian.OutputFcn property of the controller to one of the following.
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Jacobian.OutputFcn = "myOutputJacobian";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path
Jacobian.OutputFcn = @myOutputJacobian;
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
Your output Jacobian function must have one of the following signatures.
9-10
Specify Prediction Model for Nonlinear MPC
The input arguments of the output Jacobian function are the same as the inputs of the output
function. This table describes the output of the Jacobian function. Since the output function cannot
have direct feedthrough from any manipulated variable to any output, the output Jacobian function
returns only the gradients of the output function with respect to the model states.
Argument Description
C Jacobian of the output function, returned as an Ny-by-Nx array, where
C i, j = ∂y i / ∂x j .
y1 = x1
y2 = x2 + 0.2x3
y3 = x3 ⋅ x4
To find the Jacobians, compute the partial derivatives of the output equations with respect to the
states. Since the output function cannot have direct feedthrough from any manipulated variable to
any output at any time, you do not compute the Jacobian with respect to the manipulated variables.
C = zeros(3,4);
C(1,1) = 1;
C(2,2) = 1;
C(2,3) = 0.2;
C(3,3) = x(4);
C(3,4) = x(3);
The same parameters are passed to the prediction model, custom cost function, custom constraint
functions, and their respective Jacobians. For example, even if the state function uses only parameter
p1, the constraint functions use only parameter p2, and the cost function uses only parameter p3,
you must still define three parameters. All of these parameters are passed into all of these functions,
and you must choose the correct parameter to use in each function.
For an example that specifies the sample time of a discrete-time state function as a parameter, see
“Swing-Up Control of a Pendulum Using Nonlinear Model Predictive Control” on page 9-76.
9-11
9 Nonlinear MPC
your plan with a disturbance model. Doing so allows the external state estimator to detect the
disturbance and thus give the nonlinear MPC controller enough information to reject it.
During simulation, the controller passes a zero to each unmeasured disturbance input channel, since
the signals are unmeasured and assumed to be zero-mean by default.
To augment your prediction model, you must designate one or more input signals as unmeasured
disturbances when creating a controller using nlmpc. For example, create a controller where the first
two inputs are manipulated variables and the third input is an unmeasured disturbance (UD).
Specify the unmeasured disturbance model in the state and output functions of your prediction
model. This unmeasured disturbance model can be any arbitrary model that accurately captures the
effect of the disturbance on your plant. For example:
• If you expect a step-like UD at a plant output, then specify the UD model as an integrator in your
state function, and add the integrator state to the plant output in your output function.
• If you expect a ramp-like UD at a plant input, then specify the UD model as an integrator and add
the integrator output to the input signal in your state function.
Any states that you add when specifying the unmeasured disturbance model are included in the
prediction model state vector. The values in these unmeasured disturbance model states reflect the
disturbance behavior during simulation. This state vector corresponds to the x input argument of
your state function and the X input argument to your custom cost and constraint functions.
For an example that augments the prediction model for random step-like output disturbances, see
“Nonlinear Model Predictive Control of an Exothermic Chemical Reactor” on page 9-90.
See Also
Functions
validateFcns | nlmpcmove
Objects
nlmpc
Related Examples
• “Control of Quadrotor Using Nonlinear Model Predictive Control” on page 9-141
More About
• “Nonlinear MPC” on page 9-2
• “Specify Cost Function for Nonlinear MPC” on page 9-13
• “Specify Constraints for Generic Nonlinear MPC” on page 9-20
9-12
Specify Cost Function for Nonlinear MPC
• Maximize profitability
• Minimize energy consumption
When you specify a custom cost function for your nonlinear MPC controller, you can choose to either
replace or augment the standard quadratic MPC cost function. By default, an nlmpc controller
replaces the standard cost function with your custom cost function. In this case, the controller
ignores the standard tuning weights in its Weights property.
To use an objective function that is the sum of the standard costs and your custom costs, set the
Optimization.ReplaceStandardCost property of your nlmpc object to false. In this case, the
standard tuning weights specified in the Weights property of the controller contribute to the cost
function. However, you can eliminate any of the standard cost function terms by setting the
corresponding penalty weight to zero. For more information on the standard MPC cost function, see
“Standard Cost Function” on page 1-7.
For a multistage MPC controller, each stage has its own cost function, which is a function only of the
decision variables and parameters at that stage.
Before simulating your controller, it is best practice to validate your custom functions, including the
cost function and its Jacobian, using the validateFcns command.
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Optimization.CustomCostFcn = "myCostFunction";
• Handle to a function in the current working folder or on the MATLAB path
Optimization.CustomCostFcn = @myCostFunction;
9-13
9 Nonlinear MPC
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
Your custom cost function must have one of the following signatures.
function J = myCostFunction(X,U,e,data)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:
function J = myCostFunction(X,U,e,data,params)
This table describes the inputs and outputs of this function, where:
9-14
Specify Cost Function for Nonlinear MPC
Field Description
Ts Prediction model sample time, as defined in
the Ts property of the controller
CurrentStates Current prediction model states, as specified
in the x input argument of nlmpcmove
LastMV MV moves used in previous control interval,
as specified in the lastmv input argument
of nlmpcmove
References Reference values for plant outputs, as
specified in the ref input argument of
nlmpcmove
MVTarget Manipulated variable targets, as specified in
the MVTarget property of an
nlmpcmoveopt object
PredictionHoriz Prediction horizon, as defined in the
on PredictionHorizon property of the
controller
NumOfStates Number of states, as defined in the
Dimensions.NumberOfStates property of
the controller
NumOfOutputs Number of outputs, as defined in the
Dimensions.NumberOfOutputs property
of the controller
NumOfInputs Number of inputs, as defined in the
Dimensions.NumberOfInputs property of
the controller
MVIndex Manipulated variables indices, as defined in
the Dimensions.MVIndex property of the
controller
MDIndex Measured disturbance indices, as defined in
the Dimensions.MDIndex property of the
controller
UDIndex Unmeasured disturbance indices, as defined
in the Dimensions.UDIndex property of
the controller
9-15
9 Nonlinear MPC
To use output variable values in your cost function, you must first derive them from the state and
input arguments using the prediction model output function, as specified in the Model.OutputFcn
property of the controller. For example, to compute the output trajectory Y from time k to time k+p,
use:
p = data.PredictionHorizon;
for i=1:p+1
Y(i,:) = myOutputFunction(X(i,:)',U(i,:)',params)';
end
For more information on the prediction model output function, see “Specify Prediction Model for
Nonlinear MPC” on page 9-5.
Typically, you optimize control actions to minimize the cost function across the prediction horizon.
Since the cost function value must be a scalar, you compute the cost function at each prediction
horizon step and add the results together. For example, suppose that the stage cost function is:
J = 10u12 + 5x23 + x1
That is, you want to minimize the difference between the first output and its reference value, and the
product of the first manipulated variable and the second state. To compute the total cost function
across the prediction horizon, use:
p = data.PredictionHorizon;
U1 = U(1:p,data.MVIndex(1));
X1 = X(2:p+1,1);
X2 = X(2:p+1,2);
J = 10*sum(U1.^2) + 5*sum(X2.^3) + sum(X1);
In general, for cost functions, do not use the following values, since they are not part of the decision
variables used by the solver:
9-16
Specify Cost Function for Nonlinear MPC
Since this example cost function is relatively simple, you can specify it using an anonymous function
handle.
For relatively simple costs, you can specify the cost function using an anonymous function handle. For
example, to specify an anonymous function that implements just the first term of the preceding cost
function, use:
Optimization.CustomCostFcn = @(X,U,data) 10*sum(U(1:end-1,data.MVIndex(1)).^2);
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Jacobian.CustomCostFcn = "myCostJacobian";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path
Jacobian.CustomCostFcn = @myCostJacobian;
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
Your cost Jacobian function must have one of the following signatures.
The input arguments of the cost Jacobian function are the same as the inputs of the custom cost
function. This table describes the outputs of the Jacobian function, where:
9-17
9 Nonlinear MPC
Argument Description
G Jacobian of the cost function with respect to the state trajectories, returned as a
p-by-Nx array, where G i, j = ∂J / ∂X i + 1, j . Compute G based on X from the
second row to row p+1, ignoring the first row.
Gmv Jacobian of the cost function with respect to the manipulated variable
trajectories, returned as a p-by-Nmv array, where Gmv i, j = ∂ J/ ∂U i, MV j and
MV(j) is the jth MV index in data.MVIndex.
Since the controller forces U(p+1,:) to equal U(p,:), if your cost function
uses U(p+1,:), you must include the impact of both U(p,:) and U(p+1,:) in
the Jacobian for U(p,:).
Ge Jacobian of the cost function with respect to the slack variable, e, returned as a
scalar, where Ge = ∂J / ∂e.
To use output variable values and their Jacobians in your cost Jacobian function, you must first derive
them from the state and input arguments. To do so, use the Jacobian of the prediction model output
function, as specified in the Jacobian.OutputFcn property of the controller. For example, to
compute the output variables Y and their Jacobians Yjacob from time k to time k+p, use:
p = data.PredictionHorizon;
for i=1:p+1
Y(i,:) = myOutputFunction(X(i,:)',U(i,:)',params)';
end
for i=1:p+1
Yjacob(i,:) = myOutputJacobian(X(i,:)',U(i,:)',params)';
end
Since prediction model output functions do not support direct feedthrough from inputs to outputs, the
output function Jacobian contains partial derivatives with respect to only the states in X. For more
information on the output function Jacobian, see “Specify Prediction Model for Nonlinear MPC” on
page 9-5.
To find the Jacobians, compute the partial derivatives of the cost function with respect to the state
trajectories, manipulated variable trajectories, and slack variable. For example, suppose that your
cost function is as follows, where u1 is the first manipulated variable.
J = 10u12 + 5x23 + x1
To compute the Jacobian with respect to the state trajectories, use the following. Recall that you
compute G based on X from the second row to row p+1, ignoring the first row.
p = data.PredictionHorizon;
Nx = data.NumOfStates;
U1 = U(1:p,data.MVIndex(1));
X2 = X(2:p+1,2);
G = zeros(p,Nx);
G(1:p,1) = 1;
G(1:p,2) = 15*X2.^2;
To compute the Jacobian with respect to the manipulated variable trajectories, use:
Nmv = length(data.MVIndex);
9-18
Specify Cost Function for Nonlinear MPC
Gmv = zeros(p,Nmv);
Gmv(1:p,1) = 20*U1;
Note For multistage nonlinear MPC, you can automatically generate a stage cost Jacobian function
using generateJacobianFunction.
See Also
Functions
generateJacobianFunction | validateFcns | nlmpcmove
Objects
nlmpc
Related Examples
• “Economic MPC Control of Ethylene Oxide Production” on page 9-150
More About
• “Nonlinear MPC” on page 9-2
• “Economic MPC” on page 9-148
• “Specify Prediction Model for Nonlinear MPC” on page 9-5
• “Specify Constraints for Generic Nonlinear MPC” on page 9-20
9-19
9 Nonlinear MPC
• Standard linear constraints on states, outputs, manipulated variables, and manipulated variable
rates of change
• Custom equality constraints, specified as linear or nonlinear functions of the prediction model
system states and inputs
• Custom inequality constraints, specified as linear or nonlinear functions of the prediction model
system states and inputs
• Passivity inequality constraints, specified as linear or nonlinear functions of the prediction model
states and inputs
The controller optimizes its control moves to satisfy all of these constraints; that is, the custom
constraints supplement the standard linear constraints.
To improve computational efficiency, you can also specify analytical Jacobians for your custom
equality and inequality constraints.
• Require the plant to reach a target state at the end of the prediction horizon
• Require cumulative resource consumption to stay within specified limits
If your plant is passive, enforcing controller passivity guarantees that the resulting closed loop
system is stable. You can enforce controller passivity by specifying passivity constraints.
For a multistage MPC controller, each stage has its own constraints, and each constraint for a specific
stage is function only of the decision variables and parameters at that stage. Passivity constraints are
not supported for nlmpcMultistage objects.
Before simulating your controller, it is best practice to validate your custom functions, including the
constraint functions and their Jacobians, using the validateFcns command.
Linear MPC controllers have properties for defining custom constraints on linear combinations of
inputs and outputs, as discussed in “Constraints on Linear Combinations of Inputs and Outputs” on
page 5-6. These properties are not available for nonlinear MPC controllers. Instead, you implement
such constraints within your custom equality or inequality constraint functions.
9-20
Specify Constraints for Generic Nonlinear MPC
Default: 1 (soft)
Upper bounds on output OutputVariables(i).Max < OutputVariables(i).MaxEC
variable i Inf R > 0
Default: 1 (soft)
Lower bounds on manipulated ManipulatedVariables(i). ManipulatedVariables(i).
variable i Min > -Inf MinECR > 0
Default: 0 (hard)
Upper bounds on manipulated ManipulatedVariables(i). ManipulatedVariables(i).
variable i Max < Inf MaxECR > 0
Default: 0 (hard)
Lower bounds on manipulated ManipulatedVariables(i). ManipulatedVariables(i).
variable i rate of change RateMin > -Inf RateMinECR > 0
Default: 0 (hard)
Lower bounds on manipulated ManipulatedVariables(i). ManipulatedVariables(i).
variable i rate of change RateMax < Inf RateMaxECR > 0
Default: 0 (hard)
Custom Constraints
You can specify custom equality and inequality constraints for a nonlinear MPC controller. To
configure your nonlinear MPC controller to use custom equality or inequality constraints, set its
Optimization.CustomEqConFcn or Optimization.CustomIneqConFcn respectively. To do so,
specify the custom functions as one of the following.
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Optimization.CustomEqConFcn = "myEqConFunction";
Optimization.CustomIneqConFcn = "myIneqConFunction";
• Handle to a function in the current working folder or on the MATLAB path
Optimization.CustomEqConFcn = @myEqConFunction;
Optimization.CustomIneqConFcn = @myIneqConFunction;
9-21
9 Nonlinear MPC
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
This table describes the inputs and outputs of these functions, where:
9-22
Specify Constraints for Generic Nonlinear MPC
Field Description
Ts Prediction model sample time, as defined in
the Ts property of the controller
CurrentStates Current prediction model states, as specified
in the x input argument of nlmpcmove
LastMV MV moves used in previous control, as
specified in the lastmv input argument of
nlmpcmove interval
References Reference values for plant outputs, as
specified in the ref input argument of
nlmpcmove
MVTarget Manipulated variable targets, as specified in
the MVTarget property of an
nlmpcmoveopt object
PredictionHoriz Prediction horizon, as defined in the
on PredictionHorizon property of the
controller
NumOfStates Number of states, as defined in the
Dimensions.NumberOfStates property of
the controller
NumOfOutputs Number of outputs, as defined in the
Dimensions.NumberOfOutputs property
of the controller
NumOfInputs Number of inputs, as defined in the
Dimensions.NumberOfInputs property of
the controller
MVIndex Manipulated variables indices, as defined in
the Dimensions.MVIndex property of the
controller
MDIndex Measured disturbance indices, as defined in
the Dimensions.MDIndex property of the
controller
UDIndex Unmeasured disturbance indices, as defined
in the Dimensions.UDIndex property of
the controller
9-23
9 Nonlinear MPC
To use output variable values in your constraint functions, you must first derive them from the state
and input arguments using the prediction model output function, as specified in the
Model.OutputFcn property of the controller. For example, to compute the output trajectory Y from
time k to time k+p, use:
p = data.PredictionHorizon;
for i=1:p+1
Y(i,:) = myOutputFunction(X(i,:)',U(i,:)',params)';
end
For more information on the prediction model output function, see “Specify Prediction Model for
Nonlinear MPC” on page 9-5.
In general:
You can define custom constraints that apply across the entire prediction horizon. For example,
suppose that you want to satisfy the following inequality constraints across the prediction horizon,
where u1 is the first manipulated variable:
2x12 − 3x2 − 10 ≤ 0
u12 − 5 ≤ 0
9-24
Specify Constraints for Generic Nonlinear MPC
p = data.PredictionHorizon;
U1 = U(1:p,data.MVIndex(1));
X1 = X(2:p+1,1);
X2 = X(2:p+1,2);
Applying these two constraints across p prediction horizon steps produces a column vector with 2*p
inequality constraints. These inequality constraints are satisfied when the corresponding element of
cineq is less than or equal to zero.
Alternatively, you can define constraints that apply at specific prediction horizon steps. For example,
suppose that you want the states of a third-order plant to be:
x1 = 5
x2 = − 3
x3 = 0
To specify these state values as constraints on only the final prediction horizon step, use:
ceq = [X(p+1,1) - 5;
X(p+1,2) + 3;
X(p+1,3)];
These equality constraints are satisfied when the corresponding element of ceq is equal to zero.
For relatively simple constraints, you can specify the constraint function using an anonymous function
handle. For example, to specify an anonymous function that implements the equality constraints, use:
Optimization.CustomEqConFcn = @(X,U,data) [X(p+1,1) - 5; X(p+1,2) + 3; X(p+1,3)];
To specify a Jacobian for your equality or inequality constraint functions, set the respective
Jacobian.CustomEqConFcn or Jacobian.CustomIneqConFcn property of the controller to one of
the following.
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Jacobian.CustomEqConFcn = "myEqConJacobian";
Jacobian.CustomIneqConFcn = "myIneqConJacobian";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path
Jacobian.CustomEqConFcn = @myEqConJacobian;
Jacobian.CustomIneqConFcn = @myIneqConJacobian;
9-25
9 Nonlinear MPC
• Anonymous function
Jacobian.CustomEqConFcn = @(X,U,data,params) myEqConJacobian(X,U,data,params);
Jacobian.CustomInqConFcn = @(X,U,e,data,params) myIneqConJacobian(X,U,e,data,params);
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
Your constraint Jacobian functions must have one of the following signatures.
The input arguments of the constraint Jacobian functions are the same as the inputs of their
respective custom constraint functions. This table describes the outputs of the Jacobian functions,
where:
Argument Description
G Jacobian of the equality or inequality constraints with respect to the state
trajectories, returned as a p-by-Nx-by-Nc array, where
G i, j, l = ∂c l / ∂X i + 1, j . Compute G based on X from the second row to row p
+1, ignoring the first row.
Gmv Jacobian of the equality or inequality constraints with respect to the
manipulated variable trajectories, returned as a p-by-Nmv-by-Nc array, where
Gmv i, j, l = ∂c l / ∂U i, MV j and MV(j) is the jth MV index in data.MVIndex.
Since the controller forces U(p+1,:) to equal U(p,:), if your constraints use
U(p+1,:), you must include the impact of both U(p,:) and U(p+1,:) in the
Jacobian for U(p,:).
Ge Jacobian of the inequality constraints with respect to the slack variable, e,
returned as a row vector of length Nc, where Ge l = ∂c l / ∂e
To use output variable Jacobians in your constraint Jacobian functions, you must first derive them
from the state and input arguments using the Jacobian of the prediction model output function, as
specified in the Jacobian.OutputFcn property of the controller. For example, to compute the
output variable Jacobians Yjacob from time k to time k+p, use:
9-26
Specify Constraints for Generic Nonlinear MPC
p = data.PredictionHorizon;
for i=1:p+1
Y(i,:) = myOutputFunction(X(i,:)',U(i,:)',params)';
end
for i=1:p+1
Yjacob(i,:) = myOutputJacobian(X(i,:)',U(i,:)',params)';
end
Since prediction model output functions do not support direct feedthrough from inputs to outputs, the
output function Jacobian contains partial derivatives with respect to only the states in X. For more
information on the output function Jacobian, see “Specify Prediction Model for Nonlinear MPC” on
page 9-5.
To find the Jacobians, compute the partial derivatives of the constraint functions with respect to the
state trajectories, manipulated variable trajectories, and slack variable. For example, suppose that
your constraint function is as follows, where u1 is the first manipulated variable.
2x12 − 3x2 − 10 ≤ 0
u12 − 5 ≤ 0
To compute the Jacobian with respect to the manipulated variable trajectories, use:
Nmv = length(data.MVIndex);
Gmv = zeros(p,Nmv,Nc);
Gmv(1:p,1,p+1:2*p) = diag(2*u(1:p,data.MVIndex(1)));
In this case, the derivative with respect to the slack variable is Ge = zeros(20,1).
Note For multistage nonlinear MPC, you can automatically generate a stage constraint Jacobian
function using generateJacobianFunction.
Passivity Constraints
You can specify passivity inequality constraints for a general nonlinear MPC controller (multistage
MPC controllers do not support passivity constraints). To use passivity constraints, set these
properties of your nlmpc object as follows:
• Passivity.EnforceConstraint — true
• Passivity.OutputPassivityIndex — A desired nonnegative scalar
• Passivity.InputPassivityIndex — A desired nonnegative scalar
• Passivity.OutputFcn — Name of the desired passivity output function yp(x,u)
• Passivity.InputFcn — Name of the desired passivity input function up(x,u)
When your nonlinear MPC controller is configured to use passivity constraints, at each step the
optimization algorithm tries to enforce the inequality constraint:
9-27
9 Nonlinear MPC
T T T
yp(x, u) up(x, u) + νy yp(x, u) yp(x, u) + νu up(x, u) up(x, u) ≤ 0.
Here, νy is the output passivity index, νu is the input passivity index, up(x,u) is the passivity input
function, and yp(x,u) is the passivity output function. The variables x and u are the current state and
input of the prediction model.
Assuming that the plant is already passive with respect to the input-output pair up and yp, if these two
inequalities are verified, then (under mild conditions) the resulting closed loop system tends to
dissipate energy over time, and therefore has a stable equilibrium. For more information on passivity
in the context of linear systems, see “About Passivity and Passivity Indices”.
To improve computational efficiency, you can specify analytical Jacobians for your passivity constraint
functions. To do so, specify the Passivity.OutputJacobianFcn and
Passivity.InputJacobianFcn properties.
You can specify the passivity functions and their Jacobians as one of the following:
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector.
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path. For more information on local functions, see “Local Functions”.
• Anonymous function. For more information on anonymous functions, see “Anonymous Functions”.
Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.
The passivity functions and their Jacobians must accept as first and second input arguments the
current state and input of the prediction model, respectively. After the first two input arguments, you
can also pass an optional comma separated list of parameters (for example p1,p2,p3) that might be
needed by the function you specify.
If any of your functions use optional parameters, you must specify the number of parameters using
Model.NumberOfParameters. At run time, in Simulink, you then pass these parameters to the
Nonlinear MPC Controller block. In MATLAB, you pass the parameters to a simulation function (such
as nlmpcmove, using an nlmpcmoveopt option set object).
The function specified in Passivity.OutputJacobianFcn (if any) must return as a first output
argument the Jacobian matrix of the output passivity function with respect to the current state (an
Nyp-by-Nx matrix) and as a second output argument the Jacobian matrix of the output passivity
function with respect to the manipulated variables (an Nyp by Nmv matrix).
Similarly, the function specified in Passivity.InputJacobianFcn (if any) must return as a first
output argument the Jacobian of the input passivity function with respect to the current state (an Nup-
by-Nx matrix) and as a second output argument the Jacobian of the input passivity function with
respect to the manipulated variables (an Nup by Nmv matrix).
Here, Nx is the number of state variables of the prediction model, Nmv is the number of manipulated
variables, Nyp is the number of outputs of the passivity output function, and Nup is the number of
outputs of the passivity input function.
9-28
Specify Constraints for Generic Nonlinear MPC
For more detail, see the Passivity property of nlmpc. For examples, see “Control Quadruple-Tank
Using Passivity-Based Nonlinear MPC” on page 9-182 and “Control Robot Manipulator Using
Passivity-Based Nonlinear MPC” on page 9-187.
See Also
Functions
generateJacobianFunction | validateFcns | nlmpcmove
Objects
nlmpc | nlmpcMultistage
Blocks
Nonlinear MPC Controller
Related Examples
• “Control of Quadrotor Using Nonlinear Model Predictive Control” on page 9-141
• “Control Quadruple-Tank Using Passivity-Based Nonlinear MPC” on page 9-182
More About
• “Nonlinear MPC” on page 9-2
• “Specify Prediction Model for Nonlinear MPC” on page 9-5
• “Specify Cost Function for Nonlinear MPC” on page 9-13
9-29
9 Nonlinear MPC
• Predicted state values from time tk+1 to tk+p. These values correspond to rows 2 through p+1 of
the X input argument of your cost and constraint functions, where p is the prediction horizon.
• Predicted manipulated variables from time tk to tk+p-1. These values correspond to the manipulated
variable columns in rows 1 through p of the U input argument of your cost and constraint
functions.
Therefore, the number of decision variables NZ is equal to p(Nx+Nmv) + 1, Nx is the number of states,
Nmv is the number of manipulated variables, and the +1 accounts for the global slack variable.
During closed-loop simulations, it is best practice to warm start your nonlinear solver. To do so, use
the predicted state and manipulated variable trajectories from the previous control interval as the
initial guesses for the current control interval. In Simulink, the Nonlinear MPC Controller block is
configured to use these trajectories as initial guesses by default. To use these trajectories as initial
guesses at the command line:
1 Return the opt output argument when calling nlmpcmove. This nlmpcmoveopt object contains
any run-time options you specified in the previous call to nlmpcmove. It also includes the initial
guesses for the state (opt.X0) and manipulated variable (opt.MV0) trajectories, and the global
slack variable (opt.Slack0).
2 Pass this object in as the options input argument to nlmpcmove for the next control interval.
These command-line simulation steps are best practices, even if you do not specify any other run-time
options.
9-30
Configure Optimization Solver for Nonlinear MPC
These nondefault options typically improve the performance of the nonlinear MPC controller.
You can modify the solver options for your application. For example, to specify the maximum number
of solver iterations for your application, set SolverOptions.MaxIter. For more information on the
available solver options, see fmincon.
To use the C/GMRES method to solve multistage nonlinear MPC problems, specify the
Optimization.Solver property of your multistage nonlinear MPC object as "cgmres". When you
do so, the software stores a default C/GMRES options object in the Optimization.SolverOptions
property of your multistage MPC object.
The C/GMRES options object has the following properties, which you can modify using dot notation.
In inexact Newton methods, the Newton direction is typically approximated using an iterative
linear solver, such as the conjugate gradient method or the GMRES method. However, due to
9-31
9 Nonlinear MPC
computational limitations or other factors, the iterative solver may not find an exact solution to
the linear system within a specified tolerance. The forcing term is introduced to compensate for
the inexactness of the Newton direction. It adjusts the step size taken in each iteration to ensure
convergence, even when the Newton direction is not accurate enough. The forcing term can be
viewed as a trust region radius that limits the step size based on the accuracy of the Newton
direction. Therefore a decrease of the stabilization parameter normally leads to a decrease of the
step size.
For an example on how to use the C/GMRES solver, see “Control Robot Manipulator Using C/GMRES
Solver” on page 9-36.
You can use the Nonlinear Programming solver developed by Embotech AG to simulate and generate
code for nonlinear MPC controllers. For more information, see “Implement MPC Controllers Using
Embotech FORCESPRO Solvers” on page 10-73.
To configure your nlmpc object to use your custom solver wrapper function, set its
Optimization.CustomSolverFcn property in one of the following ways:
• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Optimization.CustomSolverFcn = "myNLPSolver";
• Handle to a function in the current working folder or on the MATLAB path
Optimization.CustomSolverFcn = @myNLPSolver;
This table describes the inputs and outputs of this function, where:
9-32
Configure Optimization Solver for Nonlinear MPC
[F,G] = FUN(z)
and arguments:
9-33
9 Nonlinear MPC
[cineq,c,Gineq,Geq] = NLCON(z)
and arguments:
When you implement your custom solver function, it is best practice to have your solver use the cost
and constraint gradient information provided by the nonlinear MPC controller.
If you are unable to obtain a solution using your custom solver, try to identify a special condition for
which you know the solution, and start the solver at this condition. If the solver diverges from this
initial guess:
• Check the validity of the state and output functions in your prediction model.
• If you are using a custom cost function, make sure it is correct.
• If you are using the standard MPC cost function, verify the controller tuning weights.
• Make sure that all constraints are feasible at the initial guess.
• If you are providing custom Jacobian functions, validate your Jacobians using validateFcns.
See Also
Functions
fmincon | validateFcns
Objects
nlmpc
9-34
Configure Optimization Solver for Nonlinear MPC
Related Examples
• “Optimizing Tuberculosis Treatment Using Nonlinear MPC with a Custom Solver” on page 9-97
More About
• “Nonlinear MPC” on page 9-2
• “Specify Cost Function for Nonlinear MPC” on page 9-13
9-35