---
title: "State-space lab: matrix exponentials, Riccati and Kalman"
heading: The matrix exponential by scaling and squaring, controllability and observability tests, the discrete Riccati equation by iteration, and the steady-state Kalman filter
eyebrow: S9 · Lesson 47 · State-space lab
xp: 60
---

::: hook
State-space design rests on a few computations that are easy to state and worth writing once yourself: the matrix exponential that solves $\dot x = Ax$ and discretizes plants, the rank tests that say whether a design is possible at all, and the Riccati equations behind the LQR and the Kalman filter. Libraries do these with care for large and badly conditioned problems; for the small systems of this course, simple and transparent methods work, and you can check every one against a closed form.
:::

::: play
- The curves are the entries of the first column of $e^{At}$ for $A = \begin{pmatrix} 0 & 1 \\ -2 & -3 \end{pmatrix}$: $2e^{-t} - e^{-2t}$ and $-2e^{-t} + 2e^{-2t}$, the motion from x(0) = (1, 0).
- At t = 0.5 s they're 0.845 and −0.477; your expm must reproduce them to ten digits.
- Scaling and squaring computes $e^{A/2^m}$ by a short series and squares it m times.
:::

```sim plot
view: graph
x: t = 0..5 s
y: x = -0.6..1.1
plot: 2*exp(-t) - exp(-2*t) | label: x₁(t)
plot: -2*exp(-t) + 2*exp(-2*t) | label: x₂(t)
```

::: predict
## A scalar random walk with step variance 0.0025 is measured with noise variance 0.25. Iterating the Kalman filter's Riccati recursion, what gain does it settle to?

- [ ] 0.01
- [x] About 0.095
- [ ] 0.5
- [ ] 1

::: reveal
In steady state the prior variance satisfies $P^- = P^-R/(P^- + R) + Q$, whose positive root is $(Q + \sqrt{Q^2 + 4QR})/2 = 0.0263$, giving $K = P^-/(P^- + R) = 0.095$: each measurement moves the estimate about a tenth of the way. Iteration from any positive start converges to the same value, which is what your kalman_steady must find.
:::
:::

::: nameit
## What the lab computes

- **Matrix exponential**: pick m so that $\|At\|/2^m < 0.5$, sum the Taylor series of $e^{At/2^m}$ to 20 terms, then square the result m times.
- **Controllability and observability** of a 2 × 2 system: the determinants of $(B\ \ AB)$ and $\begin{pmatrix} C \\ CA \end{pmatrix}$ must be nonzero.
- **Discrete LQR**: iterate $P \leftarrow Q + A^TPA - A^TPB(R + B^TPB)^{-1}B^TPA$ until it stops changing; then $K = (R + B^TPB)^{-1}B^TPA$. For one state the fixed point solves $b^2P^2 + (r(1 - a^2) - qb^2)P - qr = 0$.
- **Steady-state Kalman filter** for a random walk: iterate $P^- \leftarrow P^-R/(P^- + R) + Q$, with gain $K = P^-/(P^- + R)$.
:::

::: check
kind: python

## Write `expm(A, t)`: $e^{At}$ for a 2 × 2 list A by scaling and squaring.

```python starter
def expm(A, t):
    return [[1.0, 0.0], [0.0, 1.0]]
```

```python solution
def mul(X, Y):
    return [[sum(X[i][k] * Y[k][j] for k in range(2)) for j in range(2)] for i in range(2)]

def expm(A, t):
    M = [[A[i][j] * t for j in range(2)] for i in range(2)]
    norm = max(sum(abs(v) for v in row) for row in M)
    m = 0
    while norm / 2 ** m > 0.5:
        m += 1
    M = [[v / 2 ** m for v in row] for row in M]
    E = [[1.0, 0.0], [0.0, 1.0]]
    term = [[1.0, 0.0], [0.0, 1.0]]
    for k in range(1, 21):
        term = mul(term, M)
        term = [[v / k for v in row] for row in term]
        E = [[E[i][j] + term[i][j] for j in range(2)] for i in range(2)]
    for _ in range(m):
        E = mul(E, E)
    return E
```

```python tests
import math
A = [[0, 1], [-2, -3]]
for t in (0.5, 3.0):
    E = expm(A, t)
    want = [[2 * math.exp(-t) - math.exp(-2 * t), math.exp(-t) - math.exp(-2 * t)], [-2 * math.exp(-t) + 2 * math.exp(-2 * t), -math.exp(-t) + 2 * math.exp(-2 * t)]]
    assert all(abs(E[i][j] - want[i][j]) < 1e-10 for i in range(2) for j in range(2)), f"e^(At) at t = {t}."
R = expm([[0, 2], [-2, 0]], 1.0)
assert abs(R[0][0] - math.cos(2)) < 1e-12 and abs(R[0][1] - math.sin(2)) < 1e-12, "A rotation."
```

::: right
Right. Scaling keeps the series short and accurate; squaring restores the full time, doubling it m times.
:::
:::

::: check
kind: python

## Write `controllable(A, B)` and `observable(A, C)` for 2 × 2 systems (B a column as a list of 2, C a row as a list of 2), returning booleans, with a tolerance of 1e-12 on the determinant.

```python starter
def controllable(A, B):
    return True

def observable(A, C):
    return True
```

```python solution
def controllable(A, B):
    AB = [A[0][0] * B[0] + A[0][1] * B[1], A[1][0] * B[0] + A[1][1] * B[1]]
    return abs(B[0] * AB[1] - B[1] * AB[0]) > 1e-12

def observable(A, C):
    CA = [C[0] * A[0][0] + C[1] * A[1][0], C[0] * A[0][1] + C[1] * A[1][1]]
    return abs(C[0] * CA[1] - C[1] * CA[0]) > 1e-12
```

```python tests
assert controllable([[-1, 1], [0, -2]], [0, 1]), "Lesson 34's example is controllable."
assert not controllable([[-1, 0], [0, -2]], [1, 0]), "The second mode never sees the input."
assert observable([[0, 1], [0, 0]], [1, 0]) and not observable([[0, 1], [0, 0]], [0, 1]), "Position reveals velocity; velocity doesn't reveal position."
```

::: right
Right. Measuring a double integrator's velocity leaves its position unknown up to a constant: unobservable.
:::
:::

::: check
kind: python

## Write `dlqr_scalar(a, b, q, r)`: iterate the scalar discrete Riccati equation from P = q until it changes by less than 1e-14, and return (P, K).

```python starter
def dlqr_scalar(a, b, q, r):
    return q, 0.0
```

```python solution
def dlqr_scalar(a, b, q, r):
    P = q
    for _ in range(100000):
        Pn = q + a * a * P - (a * b * P) ** 2 / (r + b * b * P)
        if abs(Pn - P) < 1e-14:
            P = Pn
            break
        P = Pn
    return P, a * b * P / (r + b * b * P)
```

```python tests
import math
a, b, q, r = 1.1, 0.5, 1.0, 1.0
P, K = dlqr_scalar(a, b, q, r)
B = r * (1 - a * a) - q * b * b
assert abs(P - (-B + math.sqrt(B * B + 4 * b * b * q * r)) / (2 * b * b)) < 1e-10, "Matches the quadratic's positive root."
assert abs(a - b * K) < 1, "The closed-loop pole a − bK is inside the unit circle, though a = 1.1 isn't."
```

::: right
Right. The iteration is the dynamic-programming solution run backward in time; its fixed point is the infinite-horizon optimum.
:::
:::

::: check
kind: python

## Write `kalman_steady(Q, R)`: iterate the random-walk Kalman recursion from $P^- = R$ to convergence and return (prior variance, gain).

```python starter
def kalman_steady(Q, R):
    return R, 0.5
```

```python solution
def kalman_steady(Q, R):
    P = R
    for _ in range(100000):
        Pn = P * R / (P + R) + Q
        if abs(Pn - P) < 1e-15:
            P = Pn
            break
        P = Pn
    return P, P / (P + R)
```

```python tests
import math
for Q, R in ((0.0025, 0.25), (1.0, 1.0), (1e-4, 10.0)):
    P, K = kalman_steady(Q, R)
    Pc = (Q + math.sqrt(Q * Q + 4 * Q * R)) / 2
    assert abs(P - Pc) < 1e-9 * max(1, Pc) and abs(K - Pc / (Pc + R)) < 1e-9, f"Q = {Q}, R = {R}."
```

::: right
Right. The gain depends only on the ratio Q/R: how fast the truth wanders compared with how noisy the sensor is.
:::
:::

::: explain
## Why does iterating the Riccati recursion converge to the steady-state Kalman gain from almost any starting variance?

::: model
Each step of the recursion first adds the process noise, which pushes the variance up, and then folds in a measurement, which pulls it down by an amount that grows with the variance itself. When the variance is too large, the measurement removes more than the process noise adds, and when it's too small, the reverse, so the variance is driven toward the one value where the two balance. That balance point is the steady-state solution, and because the update is a contraction near it, iterations from any positive start approach it geometrically, which is why a filter started with a rough initial variance soon behaves as if it had been running forever.
:::
:::
