Generate MATLAB Jacobian functions for multistage nonlinear MPC using automatic differentiation
uses automatic differentiation to generate a MATLAB® function that calculates the derivatives, with respect to the plant states and
inputs, of a function specified in the multistage nonlinear MPC object
newMSobj = generateJacobianFunction(
oldMSobj and indicated by
After successfully generating and saving the function file (along with two supporting
files) in the same folder as the one in which the original function is located,
generateJacobianFunction returns the new multistage nonlinear MPC
newMSobj. This returned object is the same as the original
oldMSobj but has its corresponding Jacobian function fields (in
Stages properties) updated to use
the generated Jacobian function.
The name of the generated Jacobian function is the same of the original function with
Jacobian appended at the end. If a stage of
oldMSobj does not have any cost or constraint function defined, no
cost or constraint Jacobian function is generated for that stage.
For more information or automatic differentiation, see Automatic Differentiation Background (Optimization Toolbox).
also specifies the stage number and whether to save the generated function files in the
current folder, using one or more name-value pair arguments.
Generate Jacobian Functions for Multistage Nonlinear MPC
Create a multistage nonlinear MPC object with a horizon of ten steps, for a plant with six states and two manipulated variables.
msobj = nlmpcMultistage(10,6,2);
Write a simple state function as a string.
sstr = "function xdot = mystatefcn(x,u)" + newline + ... "xdot = ones(6,2)*u-x.^3;" + newline + "end";
Write the string to the
sfid=fopen("mystatefcn.m","w"); fwrite(sfid,sstr,"char"); fclose(sfid);
Write a simple cost function as a string.
cstr = "function c = mycostfcn(k,x,u)" + newline + ... "c = k*u'*u + k*x'*x;" + newline + "end";
Write the string to the
cfid=fopen("mycostfcn.m","w"); fwrite(cfid,cstr,"char"); fclose(cfid);
Alternatively, you can write your state and cost MATLAB functions in the current folder (local functions are supported for the generation of Jacobians, but not for the generation of deployment code).
Specify the state transition function for the prediction model (
mystatefcn is defined at the end of this example).
msobj.Model.StateFcn = "mystatefcn";
Specify the cost functions for all stages except the first two (
mycostfcn is defined at the end of the file).
for i=3:10 msobj.Stages(i).CostFcn = "mycostfcn"; end
Generate the state Jacobian function. This function calculates the derivatives of the state function with respect to the plant states and inputs.
msobj = generateJacobianFunction(msobj,"state");
Generate the cost Jacobian function. This function calculates the derivatives of each stage cost function with respect to the plant states and inputs.
msobj = generateJacobianFunction(msobj,"cost");
Display the generated cost Jacobian function.
function [Jx, Ju] = mycostfcnJacobian(stage, x, u) % This function was generated by Model Predictive Control Toolbox (Version 23.2). % 19-Aug-2023 23:17:43 %# codegen persistent ADdata if isempty(ADdata) ADdata = coder.load('mycostfcnJacobianADdata','constants'); end params.stage = stage; [~,J] = mycostfcnJacobianAD([x;u],ADdata.constants,params); Jx = J(1:6,:); Ju = J([7 8],:);
Display the Jacobian fields of the
Stages properties of
ans = 'mystatefcnJacobian'
ans = 
ans = 'mycostfcn'
Validate all the functions specified in
msobj for a random plant state and input.
Model.StateFcn is OK. Model.StateJacFcn is OK. "CostFcn" of the following stages [3 4 5 6 7 8 9 10] are OK. "CostJacFcn" of the following stages [3 4 5 6 7 8 9 10] are OK. Analysis of user-provided model, cost, and constraint functions complete.
oldMSobj — Original multistage MPC controller
Original multistage nonlinear MPC controller, specified as an
type — Type of function
Type of function for which Jacobians are generated, specified as one of the following strings:
"state"— Generate Jacobian functions for the state function.
"cost"— Generate Jacobian functions for the cost function.
"ineqcon"— Generate Jacobian functions for the inequality constraint function.
"eqcon"— Generate Jacobian functions for the equality constraint function.
Specify optional pairs of arguments as
the argument name and
Value is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
SaveInSameFolder — Option to save generated function files in same folder
1 (default) |
Option to save generated function files in the same folder as the one in which the
original function is located, specified as a numeric or logical
false). If you
set this option to
false, the generated function files are saved in
the current MATLAB folder (the folder returned by the
If the original state, cost or constraint function is specified in
oldMSobj as a handle to a local function (that is a
function defined in the same script file that you execute), then its Jacobian
function is always saved in the current folder, even if
SaveInSameFolder is specified as
StageNumber — Stage number
0 (default) | nonnegative integer
Stage number for which the Jacobian cost or constraint function must be generated,
specified as a nonnegative integer not grater than the number of stages. When you
specify a positive number, Jacobian functions are generated only for the specified
stage number. If you specify
0 (default), Jacobians are generated
for all the stages.
newMSobj — New nonlinear multistage MPC controller
Automatic differentiation currently supports only a limited set of mathematical operations, which are described in Supported Operations for Optimization Variables and Expressions (Optimization Toolbox). If your original function uses operations or functions that are not in the list, or has if-else statements or loops,
generateJacobianFunctionterminates with an error.
To generate Jacobian functions, do not preallocate any optimization variable. For example, suppose you try to generate Jacobians from a function containing the following code.This code results in the following error.
dxdt = zeros(2,1); dxdt(1) = x(1)*x(2); dxdt(2) = x(1)/x(2);Instead, use the following code.
Unable to perform assignment because value of type 'optim.problemdef.OptimizationExpression' is not convertible to 'double'.Note that you can use conditional preallocation using
dxdt = [x(1)*x(2); x(1)/x(2)];
optimexprto preallocate variables; however, doing so results in a Jacobian function that does not support C/C++ code generation for deployment. Therefore, the best practice is to avoid preallocation entirely. For more information, see Initialize Optimization Expressions (Optimization Toolbox).
Specifying the state, cost, and constraint functions in
oldMSobjas files in the current folder or in a folder on the MATLAB path is recommended. While handles to local functions are supported for Jacobian function generation, they are not supported for generation of C/C++ deployment code. For more information on local functions, see Local Functions.
Introduced in R2023a