## Generate Code and Deploy Controller to Real-Time Targets

Model Predictive Control Toolbox™ software provides code generation functionality for controllers designed
in MATLAB^{®} or Simulink^{®}.

### Code Generation in MATLAB

After designing an MPC controller in MATLAB, you can generate C code using MATLAB Coder™ and deploy it for real-time control.

To generate code for computing optimal MPC control moves for an implicit or explicit linear MPC controller:

Generate data structures from an MPC controller or explicit MPC controller using

`getCodeGenerationData`

.To verify that your controller produces the expected closed-loop results, simulate it using

`mpcmoveCodeGeneration`

in place of`mpcmove`

.Generate code for

`mpcmoveCodeGeneration`

using`codegen`

(MATLAB Coder). This step requires MATLAB Coder software.

For an example, see Generate Code to Compute Optimal MPC Moves in MATLAB.

You can also generate code for nonlinear MPC controllers that use the default
`fmincon`

solver with the SQP algorithm. To generate code for
computing optimal control moves for a nonlinear MPC controller:

Generate data structures from a nonlinear MPC controller using

`getCodeGenerationData`

.To verify that your controller produces the expected closed-loop results, simulate it using

`nlmpcmoveCodeGeneration`

in place of`nlmpcmove`

.Generate code for

`nlmpcmoveCodeGeneration`

using`codegen`

(MATLAB Coder). This step requires MATLAB Coder software.

### Code Generation in Simulink

After designing a controller in Simulink using any of the MPC blocks, you can generate code and deploy it for real-time control. You can deploy controllers to all targets supported by the following products:

Simulink Coder

Embedded Coder

^{®}Simulink PLC Coder™

Simulink Real-Time™

You can generate code for any of the Model Predictive Control Toolbox Simulink blocks.

Types of Controllers | Blocks |
---|---|

Implicit MPC controllers | |

Explicit MPC controllers | |

Gain-scheduled MPC controllers | |

Adaptive MPC controllers | |

MPC controllers for automotive applications | |

Nonlinear MPC controllers that use `fmincon`
with SQP |

For more information on generating code, see Simulation and Code Generation Using Simulink Coder and Simulation and Structured Text Generation Using Simulink PLC Coder.

**Note**

The MPC Controller, Explicit MPC Controller,
Adaptive MPC Controller, and Nonlinear MPC
Controller blocks are implemented using the MATLAB
Function (Simulink) block. To see the structure, right-click the block, and
select **Mask** > **Look Under Mask**. Then, open the MPC subsystem underneath.

**Note**

If your nonlinear MPC controller uses optional parameters, you must also
generate code for the Bus Creator block connected to the
**params** input port of the Nonlinear MPC
Controller block. To do so, place the Nonlinear MPC
Controller and Bus Creator blocks within a subsystem,
and generate code for that subsystem.

### Generate CUDA Code for Linear MPC Controllers

You can generate CUDA^{®} code for your MPC controller using GPU Coder™. For more information on supported GPUs, see GPU Computing Requirements (Parallel Computing Toolbox). For more
information on installing and setting up the prerequisite product, see Installing Prerequisite Products (GPU Coder) and Setting Up the Prerequisite Products (GPU Coder).

To generate and use GPU code in MATLAB:

Design a linear controller using an

`mpc`

object.Generate the structures for the core, states, and online data from your linear MPC controller using the

`getCodeGenerationData`

function.Optionally simulate your closed loop iteratively using the

`mpcmoveCodeGeneration`

function and the data structures created in the previous step.Create a coder configuration options object using the

`coder.gpuConfig`

function, and configure the code generation options.Generate code for the

`mpcmoveCodeGeneration`

function using the`codegen`

function and the coder configuration options object. Doing so generates a new function which uses code running on the GPU.Simulate your controller using the new generated function and the data structures.

For an example on using GPU code in MATLAB, see Use the GPU to Compute MPC Moves in MATLAB.

You can generate and use GPU code from the MPC Controller, Adaptive MPC Controller, or Explicit MPC Controller blocks.

To generate GPU code from a Simulink model containing any of these blocks, open the Configuration
Parameters dialog box by clicking **Model Settings**. Then, in
the **Code Generation** section, select **Generate GPU
code**.

For details on how to configure your model for GPU code generation, see Code Generation from Simulink Models with GPU Coder (GPU Coder).

### Sampling Rate in Real-Time Environment

The sampling rate that a controller can achieve in a real-time environment is system-dependent. For example, for a typical small MIMO control application running on Simulink Real-Time, the sample time can be as long as 1–10 ms for linear MPC and 100–1000 ms for nonlinear MPC. To determine the sample time, first test a less-aggressive controller whose sampling rate produces acceptable performance on the target. Next, decrease the sample time and monitor the execution time of the controller. You can further decrease the sample time as long as the optimization safely completes within each sampling period under normal plant operating conditions. To reduce the sample time, you can also consider using:

Explicit MPC. While explicit MPC controllers have a faster execution time, they also have a larger memory footprint, since they store precomputed control laws. For more information, see Explicit MPC Design.

A suboptimal QP solution after a specified number of maximum solver iterations. For more information, see Suboptimal QP Solution.

**Tip**

A lower controller sample time does not necessarily provide better performance. In fact, you want to choose a sample time that is small enough to give you good performance but no smaller. For the same prediction time, smaller sample times result in larger prediction steps, which in turn produces a larger memory footprint and more complex optimization problem.

### QP Problem Construction for Generated C Code

At each control interval, an implicit or adaptive MPC controller constructs a new QP problem, which is defined as:

$$\underset{x}{Min}(\frac{1}{2}{x}^{\u22ba}Hx+{f}^{\u22ba}x)$$

subject to the linear inequality constraints

$$Ax\le b$$

where

*x*is the solution vector.*H*is the Hessian matrix.*A*is a matrix of linear constraint coefficients.*f*and*b*are vectors.

In generated C code, the following matrices are used to provide
*H*, *A*, *f*, and
*b*. Depending on the type and configuration of the MPC
controller, these matrices are either constant or regenerated at each control
interval.

Constant Matrix | Size | Purpose | Implicit MPC | Implicit MPC with Online Weight Tuning | Adaptive MPC or LTV MPC |
---|---|---|---|---|---|

`Hinv` | N-by-_{M}N_{M} | Inverse of the Hessian matrix, H | Constant | Regenerated | Regenerated |

`Linv` | N-by-_{M}N_{M} | Inverse of the lower-triangular Cholesky decomposition of
H | |||

`Ac` | N-by-_{C}N_{M} | Linear constraint coefficients, A | Constant | ||

`Kx` | N-by-(_{xqp}N–1)_{M} | Used to generate f | Regenerated | ||

`Kr` | p*N-by-(_{y}N–1)_{M} | ||||

`Ku1` | N-by-(_{mv}N–1)_{M} | ||||

`Kv` | (N+1)*(_{md}p+1)-by-(N–1)_{M} | ||||

`Kut` | p*N-by-(_{mv}N–1)_{M} | ||||

`Mlim` | N-by-1_{C} | Used to generate b | Constant | Constant, except when there are custom constraints | |

`Mx` | N-by-_{C}N_{xqp} | Regenerated | |||

`Mu1` | N-by-_{C}N_{mv} | ||||

`Mv` | N-by-(_{C}N+1)*(_{md}p+1) |

Here:

*p*is the prediction horizon.*N*is the number of manipulated variables._{mv}*N*is the number of measured disturbances._{md}*N*is the number of output variables._{y}*N*is the number of optimization variables (_{M}*m***N*+1, where_{mv}*m*is the control horizon).*N*is the number of states used for the QP problem; that is, the total number of the plant states and disturbance model states._{xqp}*N*is the total number of constraints._{C}

At each control interval, the generated C code computes *f* and
*b* as:

$$f=K{x}^{\u22ba}\ast {x}_{q}+K{r}^{\u22ba}\ast {r}_{p}+Ku{1}^{\u22ba}\ast {m}_{l}+K{v}^{\u22ba}\ast {v}_{p}+Ku{t}^{\u22ba}\ast {u}_{t}$$

$$b=-\left(Mlim+Mx\ast {x}_{q}+Mu1\ast {m}_{l}+Mv\ast {v}_{p}\right)$$

where

*x*is the vector of plant and disturbance model states estimated by the Kalman filter._{q}*m*is the manipulated variable move from the previous control interval._{l}*u*is the manipulated variable target._{t}*v*is the sequence of measured disturbance signals across the prediction horizon._{p}*r*is the sequence of reference signals across the prediction horizon._{p}

**Note**

When generating code in MATLAB, the `getCodeGenerationData`

command generates
these matrices and returns them in `configData`

.

### Code Generation for Custom QP Solvers

You can generate code for linear MPC controllers that use a custom QP solver written in C or MATLAB code. The controller calls this solver in place of the built-in QP solver at each control interval.

For an example, see Simulate and Generate Code for MPC Controller with Custom QP Solver. For more information on custom QP solvers, see Custom QP Solver.

For information on using the FORCESPRO solver, see Implement MPC Controllers Using Embotech FORCESPRO Solvers.

## See Also

### Functions

### Objects

`mpc`

|`mpcstate`

|`mpcmoveopt`

### Blocks

- MPC Controller | Multiple MPC Controllers | Explicit MPC Controller | Multiple Explicit MPC Controllers | Adaptive MPC Controller | Nonlinear MPC Controller

## Related Examples

- Simulation and Code Generation Using Simulink Coder
- Generate Code to Compute Optimal MPC Moves in MATLAB
- Simulation and Structured Text Generation Using Simulink PLC Coder