Computing Library › Worked Examples
Worked Examples

One MPC Optimization Step

Solve a single model-predictive-control problem: minimize a quadratic cost over a short horizon, apply only the first control, then repeat.

Problem

Model predictive control (MPC) optimizes a sequence of future control inputs over a finite horizon using a model, applies only the first input, then re-solves at the next step with fresh measurements. This receding horizon gives feedback and lets you enforce constraints directly.

Setup

Kronos motion — materials first

Take a scalar system x_{k+1} = x_k + u_k with current x0=2 and target 0. Over a horizon N=3 we minimize sum of x_k^2 + 0.1 u_k^2. We solve the small quadratic program for the optimal control sequence and keep only u0.

python
import numpy as np
N=3; x0=2.0; r=0.1
# build prediction x = x0 + cumulative sum of u
# minimize ||x||^2 + r||u||^2 over u in R^N
L=np.tril(np.ones((N,N)))          # x_k depends on u_0..u_{k-1}
H=2*(L.T@L + r*np.eye(N))
f=2*(L.T@(x0*np.ones(N)))
u=np.linalg.solve(H,-f)
print('optimal sequence',np.round(u,3))
print('applied u0',round(u[0],3))

Result

The optimizer front-loads control effort: the first move is the largest because acting early drives the state toward zero for the rest of the horizon. Only u0 is applied; at the next step the state is remeasured and the whole plan is recomputed, which is what makes MPC robust to model error and disturbances.