# generateJacobianFunction

Generate MATLAB Jacobian functions for multistage nonlinear MPC using automatic differentiation

Since R2023a

## Syntax

``newMSobj = generateJacobianFunction(oldMSobj,type)``
``generateJacobianFunction(___,Name=Value)``

## Description

example

````newMSobj = generateJacobianFunction(oldMSobj,type)` 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 `oldMSobj` and indicated by `type`.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 object `newMSobj`. This returned object is the same as the original object `oldMSobj` but has its corresponding Jacobian function fields (in its `Model` and `Stages` properties) updated to use the generated Jacobian function.The name of the generated Jacobian function is the same of the original function with the `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).```
````generateJacobianFunction(___,Name=Value)` 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.```

## Examples

collapse all

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 `mystatefcn.m` file.

```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 `mycostfcn.m` file.

```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.

`type mycostfcnJacobian.m`
```function [Jx, Ju] = mycostfcnJacobian(stage, x, u) % This function was generated by Model Predictive Control Toolbox (Version 24.1). % 13-Feb-2024 00:15:44 %# 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 `Model` and `Stages` properties of `msobj`.

`msobj.Model.StateJacFcn`
```ans = 'mystatefcnJacobian' ```
`msobj.Stages(2).CostFcn`
```ans = [] ```
`msobj.Stages(3).CostFcn`
```ans = 'mycostfcn' ```

Validate all the functions specified in `msobj` for a random plant state and input.

`validateFcns(msobj,rand(6,1),rand(2,1));`
```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. ```

## Input Arguments

collapse all

Original multistage nonlinear MPC controller, specified as an `nlmpcMultistage` object.

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.

### Name-Value Arguments

Specify optional pairs of arguments as `Name1=Value1,...,NameN=ValueN`, where `Name` is 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.

Example: `FunctionName="computeAction"`

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 `1` (`true`) or `0` (`false`). If you set this option to `false`, the generated function files are saved in the current MATLAB folder (the folder returned by the `pwd` command).

Note

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 `true`.

Example: `SaveInSameFolder=false`

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.

Example: `StageNumber=3`

## Output Arguments

collapse all

New nonlinear multistage MPC controller, returned as an `nlmpcMultistage` object. It is the same as the original object `oldMSobj` but has its corresponding Jacobian function fields (in its `Model` and `Stages` properties) updated to use the generated MATLAB function.

## Limitations

• 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, `generateJacobianFunction` terminates 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.

```dxdt = zeros(2,1); dxdt(1) = x(1)*x(2); dxdt(2) = x(1)/x(2); ```
This code results in the following error.
```Unable to perform assignment because value of type 'optim.problemdef.OptimizationExpression' is not convertible to 'double'.```
`dxdt = [x(1)*x(2); x(1)/x(2)];`
Note that you can use conditional preallocation using `optimexpr` to 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 `oldMSobj` as 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.

## Version History

Introduced in R2023a