# MPC Controller

Compute MPC control law

## Description

The MPC Controller block receives the current measured output signal (`mo`), reference signal (`ref`), and optional measured disturbance signal (`md`). The block computes the optimal manipulated variables (`mv`) by solving a quadratic program (QP).

To use the block in simulation and code generation, you must specify an `mpc` object, which defines a model predictive controller. This controller must have already been designed for the plant that it will control.

Because the MPC Controller block uses MATLAB Function blocks, it requires compilation each time you change the MPC object and block. Also, because MATLAB® does not allow compiled code to reside in any MATLAB product folder, you must use a non-MATLAB folder to work on your Simulink® model when you use MPC blocks.

## Dialog Box

The MPC Controller block has the following parameter groupings:

### Parameters

#### MPC controller

You must provide a traditional (implicit) `mpc` object that defines your controller using one of the following methods:

• Enter the name of an `mpc` object in the MPC Controller edit box. This object must be present in the MATLAB workspace.

If you want to modify the controller settings in a graphical environment, click Design to open the MPC Designer app. For example, you can:

• Import a new prediction model.

• Change horizons, constraints, and weights.

• Evaluate MPC performance with a linear plant.

• Export the updated controller to the MATLAB workspace.

To see how well the controller works for the nonlinear plant, run a closed-loop Simulink simulation.

• If you do not have an existing `mpc` object in the MATLAB workspace, leave the MPC controller field empty. With the MPC Controller block connected to the plant, click Design to open the MPC Designer app. Using the app, linearize the Simulink model at a specified operating point, and design your controller. For more information, see Design MPC Controller in Simulink and Linearize Simulink Models Using MPC Designer.

To use this design approach, you must have Simulink Control Design™ software.

If you specified a controller in the MPC Controller field, click Review to review you design for run-time stability and robustness issues. For more information, see Review Model Predictive Controller for Stability and Robustness Issues.

#### Initial controller state

Specifies the initial controller state. If this parameter is left blank, the block uses the nominal values that are defined in the `Model.Nominal` property of the `mpc` object. To override the default, create an `mpcstate` object in your workspace, and enter its name in the field.

### Required Inports

Measured output or State estimate

If your controller uses default state estimation, this inport is labeled `mo`. Connect this inport to the measured signals from the plant.

If your controller uses custom state estimation, check Use custom estimated states instead of measured outputs in the General tab. Checking that option changes the label on this inport to `x[k|k]`. Connect a signal providing the controller state estimates. (The controller state includes the plant, disturbance, and noise model states.) The estimates supplied at time tk must be based on the measurements and other data available at time tk.

Reference

The `ref` dimension must not change from one control instant to the next. Each element must be a real number.

When `ref` is a 1-by-ny signal, where ny is the number of outputs, there is no reference signal previewing.  All the current values are applied across the prediction horizon.

To use signal previewing, specify `ref` as an N-by-ny signal, where N is the number of time steps for which you are specifying reference values. Here, $1, and p is the prediction horizon. Previewing usually improves performance since the controller can anticipate future reference signal changes. The first row of `ref` specifies the ny references for the first step in the prediction horizon (at the next control interval k = 1), and so on for N steps. If N < p, the last row designates constant reference values for the remaining p - N steps.

For example, suppose ny = 2 and p = 6. At a given control instant, the signal connected to the `ref` inport is:

```[2 5 ← k=1 2 6 ← k=2 2 7 ← k=3 2 8] ← k=4 ```

The signal informs the controller that:

• Reference values for the first prediction horizon step k = 1 are `2` and `5`.

• The first reference value remains at `2`, but the second increases gradually.

• The second reference value becomes `8` at the beginning of the fourth step k = 4 in the prediction horizon.

• Both values remain constant at `2` and `8` respectively for steps 5–6 of the prediction horizon.

`mpcpreview` shows how to use reference previewing in a specific case. For calculation details on the use of the reference signal, see Optimization Problem.

### Required Outports

#### Manipulated Variables

The `mv` outport provides a signal defining the ${n}_{u}\ge 1$ manipulated variables, which are to be implemented in the plant. The controller updates its `mv` outport by solving a quadratic program at each control instant.

#### Measured disturbance

Add an inport (`md`) to which you can connect a measured disturbance signal.

The `md` dimension must not change from one control instant to the next. Each element must be a real number.

When `md` is a 1-by-nmd signal, where ${n}_{md}\ge 1$ is the number of measured disturbances defined for your controller, there is no measured disturbance previewing.  All the current values are applied across the prediction horizon.

To use disturbance previewing, specify `ref` as an N-by-nmd signal, where N is the number of time steps for which the MD is known. Here, $1, and p is the prediction horizon. Previewing usually improves performance since the controller can anticipate future disturbances. The first row of `md` specifies the nmd current disturbance values (k=1), with other rows specifying disturbances for subsequent control intervals. If N < p + 1, the last row designates constant reference values for the remaining p - N + 1 steps.

For example, suppose nmd = 2 and p = 6. At a given control instant, the signal connected to the `md` inport is:

```[2 5 ← k=0 2 6 ← k=1 2 7 ← k=2 2 8] ← k=3 ```

This signal informs the controller that:

• The current `MD` values are `2` and `5` at k = 0.

• The first `MD` remains at `2`, but the second increases gradually.

• The second `MD` becomes `8` at the beginning of the third stepk = 3 in the prediction horizon.

• Both values remain constant at `2` and `8` respectively for steps 4–6 of the prediction horizon.

`mpcpreview` shows how to use `MD` previewing in a specific case.

For calculation details, see MPC Modeling and QP Matrices.

#### External manipulated variable

Add an inport (`ext.mv`), which you can connect to the actual manipulated variables (MV) used in the plant. The block uses these to update its internal state estimates.

Controller state estimation assumes that the MV is piecewise constant. At time tk, the `ext.mv` value must be the effective MV between times tk–1 and tk. For example, if the MV is actually varying over this interval, you might supply the time-averaged value evaluated at time tk.

The following example, from the model `mpc_bumpless`, includes a switch that can override the controller's output with a signal supplied by the operator. Also, the controller output may saturate. Feeding back the actual MV used in the plant (labeled `u(t)` in the example) improves the accuracy of controller state estimates.

If the external MV option is inactive or the `ext.mv` inport in unconnected, the controller assumes that its MV output is used in the plant without modification.

 Note   There is direct feed through from the `ext.mv` inport to the `mv` outport. Thus, use of this option may cause an algebraic loop in the Simulink diagram. In the above examples, the insertion of a unit delay block avoids an algebraic loop.

#### Optimal cost

Add an outport (`cost`) that provides the optimal quadratic programming objective function value at the current time (a nonnegative scalar). If the optimization problem is infeasible, however, the value is meaningless. (See `qp.status`.)

#### Optimal control sequence

Add an outport (`mv.seq`) that provides the computed optimal `MV` sequence for the entire prediction horizon from `k=0` to `k = p-1`. If nu is the number of MVs and p is the length of the prediction horizon, this signal is a p by nu matrix. The first row represents `k=0` and duplicates the block's MV outport.

The following block diagram (from Analysis of Control Sequences Optimized by MPC on a Double Integrator System) illustrates how to use this option. The diagram shows how to collect diagnostic data and send it to the To Workspace2 block, which creates the variable, `useq`, in the workspace. Run the example to see how the optimal sequence evolves with time.

#### Optimization status

Add an outport (`qp.status`) that allows you to monitor the status of the QP solver.

If a QP problem is solved successfully at a given control interval, the `qp.status` output returns the number of QP solver iterations used in computation. This value is a finite, positive integer and is proportional to the time required for the calculations. Thus, a large value means a relatively slow block execution at this time interval.

The QP solver may fail to find an optimal solution for the following reasons:

• `qp.status = 0` — The QP solver cannot find a solution within the maximum number of iterations specified in the `mpc` object.

• `qp.status = -1` — The QP solver detects an infeasible QP problem. See Monitoring Optimization Status to Detect Controller Failures for an example where a large, sustained disturbance drives the OV outside its specified bounds.

• `qp.status = -2` — The QP solver has encountered numerical difficulties in solving a severely ill-conditioned QP problem.

For all the previous three failure modes, the MPC Controller block holds its `mv` output at the most recent successful solution. In a real-time application, you can use status indicator to set an alarm or take other special action.

The next diagram shows how to use the status indicator to monitor the MPC Controller block in real time. See Monitoring Optimization Status to Detect Controller Failures for more details.

#### Estimated plant, disturbance, and noise model states

Add an outport (`est.state`) to receive the controller state estimates, `x[k|k]`, at each control instant. These include the plant, disturbance and noise model states.

### State Estimation (General tab)

#### Use custom estimated states instead of measured outputs

Replace `mo` with the `x[k|k]` inport for custom state estimation as described in Required Inports.

### Constraints (Online Features tab)

#### Plant input and output limits

Add inports (`umin`, `umax`, `ymin`, `ymax`) that you can connect to run-time constraint signals.

`umin` and`umax` are vectors with nu elements. `ymin` and`ymax` are vectors with ny elements.

If any of these inports are unconnected, they are treated as unbounded signals. The corresponding variable in the `mpc` object must also be unbounded.

For connected inports, the following rules apply:

• All connected signals must be finite. Simulink does not support infinite signals.

• If a variable is unconstrained in the controller object, the connected value is ignored.

If this check box is not selected, the block uses the constant constraint values stored within its `mpc` object.

 Note:   You cannot specify time-varying constraints at run time using a matrix signal.

### Weights (Online Features tab)

A controller intended for real-time applications should have "knobs" you can use to tune its performance when it operates with the real plant. This group of optional inports serves that purpose.

The diagram shown below shows three of the MPC Controller tuning inports. In this simulation context, the inports are tuned using pre-stored signals (the `ywt`, `duwt`, and `ECRwt` variables in the From Workspace blocks). In practice, you would connect a knob or similar manual adjustment.

 Note:   You cannot specify time-varying weights at run time using a matrix signal.

#### Weights on plant outputs

Add an inport (`y.wt`) for a vector signal with ny elements. Each element specifies a nonnegative tuning weight for each controlled output variable (OV). This signal overrides the `MPCobj.Weights.OV` property of the `mpc` object, which establishes the relative importance of OV reference tracking.

For example, if the preceding controller defined three OVs, the signal connected to the `y.wt` inport should be a vector with three elements. If the second element is relatively large, the controller would place a relatively high priority on making OV(2) track the `r(2)` reference signal. Setting a `y.wt` signal to zero turns off reference tracking for that OV.

If you do not connect a signal to the `y.wt` inport, the block uses the OV weights specified in your MPC object, and these values remain constant.

#### Weights on manipulated variables

Add an inport (`u.wt`), whose input is a vector signal defining nu nonnegative weights, where nu is the number of manipulated variables (MVs). The input overrides the `MPCobj.Weights.MV` property of the `mpc` object, which establishes the relative importance of MV target tracking.

For example, if your controller defines four MVs and the second `u.wt` element is relatively large, the controller would try to keep MV(2) close to its specified target (relative to other control objectives).

If you do not connect a signal to the `u.wt` inport, the block uses the `Weights.MV` weights property specified in your `mpc` object, and these values remain constant.

#### Weights on manipulated variable changes

Add an inport (`du.wt`), for a vector signal defining nu nonnegative weights, where nu is the number of manipulated variables (MVs). The input overrides the `MPCobj.Weights.MVrate` property of the `mpc` object, which establishes the relative importance of MV changes.

For example, if your controller defines four MVs and the second `du.wt` element is relatively large, the controller would use relatively small changes in the second MV. Such move suppression makes the controller less aggressive. However, too much suppression makes it sluggish.

If you do not connect a signal to the `du.wt` inport, the block uses the `Weights.MVrate` property specified in your `mpc` object, and these values remain constant.

#### Weight on overall constraint softening

Add an inport (`ECR.wt`), for a scalar nonnegative signal that overrides the `mpc` controller's `MPCobj.Weights.ECR` property. This inport has no effect unless your controller object defines soft constraints whose associated ECR values are nonzero.

If there are soft constraints, increasing the `ECR.wt` value makes these constraints relatively harder. The controller then places a higher priority on minimizing the magnitude of the predicted worst-case constraint violation.

You may not be able to avoid violations of an output variable constraint. Thus, increasing the `ECR.wt` value is often counterproductive. Such an increase causes the controller to pay less attention to its other objectives and does not help reduce constraint violations. You usually need to tune `ECR.wt` to achieve the proper balance in relation to the other control objectives.

### MV Targets (Online Features tab)

#### Targets for manipulated variables

If you want one or more manipulated variable (MV) to track a target value that changes with time, use this option to add an `mv.target` inport to which you can connect the target signal (dimension nu, where nu is the number of MVs).

For this to be effective, the corresponding MV(s) must have nonzero penalty weights (these weights are zero by default).

### Default Conditions tab

Specify the default block sample time and signal dimensions for performing simulation, trimming, or linearization.  In these cases, the `mv` output signal remains at zero. You must specify default condition values that are compatible with your Simulink model design.

 Note:   These default conditions apply only if the MPC Controller field is empty. If you specify a controller from the MATLAB workspace, the sample time and signal sizes from the specified controller are used.

#### Sample Time

Specify the default controller sample time.

#### Plant Input Signal Sizes

Specify the default signal dimensions for the following input signal types:

• Manipulated variables

• Unmeasured disturbances

• Measured disturbances

 Note:   You can specify the measured disturbances signal dimension only if, on the General tab, in the Additional Inports section, the Measured disturbance option is selected.

#### Plant Output Signal Sizes

Specify the default signal dimensions for the following output signal types:

• Measured outputs

• Unmeasured outputs

### Others tab

#### Block data type

Specify the block data type as one of the following:

• `double` — Double-precision floating point (default).

• `single` — Single-precision floating point.

Specify the output data type as `single` if you are implementing the MPC Controller block on a single-precision target.

For an example of double-precision and single-precision simulation and code generation for an MPC controller, see Simulation and Code Generation Using Simulink Coder.

To view the port data types in a model, in the Simulink Editor, select Display > Signals & PortsPort Data Types.

#### Inherit sample time

Use the sample time inherited from the parent subsystem as the MPC Controller block's sample time.

Inheriting the sample time allows you to conditionally execute the MPC Controller block inside the Function-Call Subsystem or Triggered Subsystem blocks. For an example, see Using MPC Controller Block Inside Function-Call and Triggered Subsystems.

 Note:   When you place an MPC controller block inside a Function-Call Subsystem or Triggered Subsystem block, you must execute the subsystem at the controller's design sample rate. You may see unexpected results if you use an alternate sample rate.

To view the sample time of a block, in the Simulink Editor, select Display > Sample Time. Select Colors, Annotations, or All. For more information, see View Sample Time Information.

#### Use external signal to enable or disable optimization

Add an inport (`switch`) whose input specifies whether the controller performs optimization calculations. If the input signal is zero, the controller behaves normally. If the input signal becomes nonzero, the MPC Controller block turns off the controller optimization calculations. This action reduces computational effort when the controller output is not needed, such as when the system is operating manually or another controller has taken over. The controller, however, continues to update its internal state estimate in the usual way. Thus, it is ready to resume optimization calculations whenever the `switch` signal returns to zero. While the controller optimization is turned off, the MPC Controller block passes the current `ext.mv` signal to the controller output. If the `ext.mv` inport is not enabled, the controller output is held at whatever value it had when the optimization was disabled.