Linear ODE systems, the matrix exponential and phase portraits
Construct the matrix exponential, classify planar phase portraits, solve systems with inputs using Duhamel, prove Liouville’s formula and discretize continuous systems for state space models.
After this lesson you can
Define the matrix exponential by its series and compute it by diagonalization and in the defective case.
Solve x′ = Ax and classify planar equilibria by trace and determinant.
Solve systems x′ = Ax + Bu with Duhamel’s formula and discretize them by zero-order hold.
Prove det(e^{tA}) = e^{t·tr A} and interpret it as volume change.
Implement matrix exponential by scaling and squaring and validate against scipy.linalg.expm.
The previous lesson gave general guarantees (Picard–Lindelöf, Grönwall) and a few tricks for individual equations. Almost no interesting ODE has a closed-form solution. One family, however, is completely solvable: constant-coefficient linear systems, x′=Ax. It matters far more than its simplicity suggests:
Linearization is looking through A. Near equilibrium any dynamics x′=f(x) resembles x′=Jx, where J is the Jacobian there. Eigenvalue lessons about J apply to pendulums, circuits, ecosystems and control loops. The next lesson makes this a theorem.
State space models are linear systems with input. S4 and Mamba, studied in sequence architectures, begin from x′=Ax+Bu, discretize at step Δ and obtain a recurrence trained as a convolution. Model memory is determined by eigenvalues of A and step Δ.
Recurrent networks and the Kalman filter have the same linear object in discrete time: xk+1=Fxk. Vanishing or exploding gradients are a spectral issue appearing here in continuous time.
Control (LQR, robot stabilization) works with x′=Ax+Bu and determines closed-loop stability from eigenvalue locations.
This lesson does four things. First construct the matrix exponentialetA, playing the role of eat for x′=ax. Then calculate it in the three Jordan-form cases and classify planar phase portraits by trace and determinant. Next solve systems with input (Duhamel’s formula) and prove Liouville’s formula for volume scaling. Finally prepare for computation: exact discretization and numerical matrix exponentiation by scaling and squaring.
From a number to a matrix
For one number, x′=ax with x(0)=x0 has solution x(t)=eatx0. With n coupled variables the equation has exactly the same form.
This is the simplest possible first-order ODE and also the destination of any higher-order linear ODE. For example y′′+3y′+2y=0 reduces, with x=(y,y′), to
x′=[0−21−3]x,
and the characteristic polynomial of that A is λ2+3λ+2, the same obtained by trying y=eλt in the second-order equation (the previous lesson’s second-order linear ODE). Eigenvalues of A are the characteristic roots.
Existence, uniqueness and superposition
Proof
Field f(x)=Ax is globally Lipschitz with constant ∥A∥ because ∥Ax−Ay∥≤∥A∥∥x−y∥. Picard–Lindelöf gives a unique local solution. It cannot explode in finite time: ∥x(t)∥≤∥x0∥+∥A∥∫0t∥x(s)∥ds and Grönwall yield ∥x(t)∥≤∥x0∥e∥A∥∣t∣, so it remains bounded on every bounded interval and extends to all R.
Differentiation is linear: if x and y are solutions and α,β∈R, then (αx+βy)′=αAx+βAy=A(αx+βy). By uniqueness, the solution with initial value αx0+βy0 is αx+βy, so x0↦x(t) is linear. It is injective because solutions coinciding at an instant t coincide forever (uniqueness holds backward too), hence bijective. The solution space is isomorphic to Rn via x↦x(0).
∎
This superposition principle makes the linear case special: solve n independent initial problems (for example x0=e1,…,en) and all other solutions are combinations. The matrix with these n solutions as columns, Φ(t)=[x(1)(t)⋯x(n)(t)], is the fundamental matrix, and general solution is x(t)=Φ(t)x0. What is Φ(t)?
The matrix exponential
If A were a number, the solution would be etAx0. We must define etA. The exponential power series makes sense for matrices because it uses only sums and products.
Does it converge? Yes, always. Choose a submultiplicative matrix norm (for example one induced by a vector norm), so Ak≤∥A∥k. Then ∑kAk/k!≤∑k∥A∥k/k!=e∥A∥<∞: the series converges absolutely for every A in complete space Rn×n (likewise for Cn×n), and eA≤e∥A∥. With tA instead of A, for ∣t∣≤T terms are bounded by (T∥A∥)k/k! independent of t: by the Weierstrass M-test (uniform convergence), the etA series converges uniformly on [−T,T], as does its derivative series, so lesson 14’s limit-interchange theorems permit termwise differentiation (an exercise below).
Proof
(3) Since (PAP−1)k=PAkP−1, take P and P−1 outside the series (summation is continuous linear). (4) Likewise: (Ak)⊤=(A⊤)k. (5) Since A and B commute, the binomial theorem gives (A+B)m=∑j=0m(jm)AjBm−j, hence
The second equality is the Cauchy product of two absolutely convergent series. (1) and (2) follow from (5) with commuting tA and sA, and B=−A.
∎
Condition AB=BA in (5) is not a technicality. With A=[0010] and B=A⊤ (noncommuting), eAeB=[2111] and eBeA=[1112] already differ, whereas eA+B=[cosh1sinh1sinh1cosh1]≈[1.5431.1751.1751.543] is neither. This reappears as a common mistake.
etA solves the system
Proof
By property (1), he(t+h)A−etA=etAhehA−I. It suffices to show the last quotient tends to A as h→0. Subtracting A and using the series,
Thus the derivative is etAA, also AetA because A commutes with every power of itself. Hence x(t)=etAx0 solves the equation and x(0)=x0. It is unique: if y is another solution, z(t)=e−tAy(t) satisfies z′=−Ae−tAy+e−tAAy=0, so z is constant and equal to z(0)=x0, and y(t)=etAx0.
∎
The fundamental matrix with Φ(0)=I is therefore Φ(t)=etA. It is the system’s flow: the motion carrying each point x0 to its position t seconds later. Property (1), e(s+t)A=esAetA, says flowing for s then t equals flowing for s+t; (2) says it can always be reversed. The next interactive shows its effect on a figure.
InteractiveThe exponential flow transports shapes
Relative area versus t (logarithmic scale)
measured polygon area
ettrA (Liouville)
figure at time t
initial figure
paths of four vertices
etA=[0.521.34−1.340.52]
Entries of A
trA0.60
Current / initial area (measured)2.0544
ettrA2.0544
detetA2.0544
trA>0: the flow expands area at a constant rate on a logarithmic scale.
A letter F (chosen because it is asymmetric, making flips visible) is transported by etA, and trajectories of four vertices follow the equation. Explore examples. With antisymmetric A the figure rotates without deformation. With a nilpotent Jordan block it shears and slides. With a saddle it stretches along one axis and contracts along the other. In each case measured area equals ettrA (dashed curve, straight on a log scale). Edit A entries and find a nonzero matrix with zero trace: what happens to area? We prove it in the Liouville section.
How to calculate it: three cases
Defining etA by a series is not calculating it. By property (3), bring A to a form where the series sums itself. Jordan form offers three cases, all visible in 2×2.
Diagonalizable with real eigenvalues
If A=PΛP−1 with Λ=diag(λ1,…,λn) (diagonalization), then Λk=diag(λik) and the series sums entrywise:
Each eigenvector vi is a direction the flow does not rotate: on its line dynamics are scalar x′=λix. In the earlier example A=[0−21−3] has eigenvalues −1 and −2 with eigenvectors (1,−1) and (1,−2), and
etA=[2e−t−e−2t−2e−t+2e−2te−t−e−2t−e−t+2e−2t].
Check it equals I at t=0 and its derivative at 0 is A. Its first row applied to (y0,y0′) recovers classical solution y(t)=c1e−t+c2e−2t.
Complex eigenvalues: rotate and scale
A real matrix can have complex eigenvalues, always conjugate pairs α±iβ (complex eigenvalues from linear algebra lesson 10). In a suitable real basis A is the block
C=[αβ−βα]=αI+βJ,J=[01−10].
Since αI commutes with everything, (5) gives etC=eαteβtJ. Since J2=−I, powers of J repeat with period 4 and the eβtJ series separates even terms (giving cosβt⋅I) from odd terms (giving sinβt⋅J): Euler’s formula for a matrix,
etC=eαt[cosβtsinβt−sinβtcosβt].
A rotation at angular speed β and factor eαt: solutions are logarithmic spirals entering if α<0, leaving if α>0 and closing into circles (ellipses in the original basis) if α=0. Generally write A=PCP−1 using real and imaginary parts of a complex eigenvector, as in lesson 10’s real-form theorem.
Repeated and defective eigenvalues
When an eigenvector is missing, A reduces only to a Jordan block. For Jλ=[λ01λ]=λI+N with N=[0010], N2=0 and N commutes with λI, so the etN series stops after two terms:
etJλ=eλt(I+tN)=eλt[10t1].
A polynomial factorteλt appears that no diagonalizable solution has. In a block of size m, Nm=0 and the exponential contains powers of t through tm−1. Since every real matrix is PJP−1 with block J, a general result follows without further calculation.
Read this from the Jordan exponential: tkeαt tends to zero if α<0 for every k, because the exponential beats every polynomial, while tkeαt with k≥1 and α=0 grows unboundedly. Thus shear J0 (double defective eigenvalue 0) has solutions escaping linearly even though no eigenvalue has positive real part.
Planar phase portraits
For n=2 we can see dynamics. A plane point x=(x1,x2) is a state, solution t↦etAx0 traces a curve, and all such curves form the system’s portrait.
The origin is always an equilibrium. Portrait shape near it is determined by spectrum of A, and for 2×2 spectrum depends only on trace and determinant. With τ=trA and δ=detA, eigenvalues are λ=2τ±τ2−4δ, hence:
Region of (τ,δ) plane
Eigenvalues
Portrait
δ<0
real, opposite signs
saddle: unstable
δ>0, τ2>4δ, τ<0
real, both negative
stable node (sink)
δ>0, τ2>4δ, τ>0
real, both positive
unstable node (source)
τ2<4δ, τ<0
α±iβ, α<0
stable focus: inward spiral
τ2<4δ, τ>0
α±iβ, α>0
unstable focus: outward spiral
τ=0, δ>0
±iβ
center: closed orbits, stable but not asymptotically
τ2=4δ=0
repeated real
degenerate node (one eigenvector) or star node (A=λI)
δ=0
at least one zero eigenvalue
nonisolated equilibrium: a line of equilibria (whole plane if A=0)
All fits in the trace–determinant plane: horizontal axis τ, vertical δ, and parabola δ=τ2/4 separates nodes below from foci above. The interactive draws the exact portrait with etAx0 forward and backward in time.
InteractiveThe trace–determinant plane and its phase portrait
(τ,δ) plane
Phase portrait of x′=Ax
trajectories etAx0
eigenline of larger λ
eigenline of smaller λ
your trajectories
A=[−2.00−1.503.001.00]
Entries of A
τ=trA−1.00
δ=detA2.50
τ2−4δ−9.00
Eigenvalues−0.50 ± 1.50 i
Portraitstable focus
Complex eigenvalues α±iβ: rotation at frequency β and growth eαt. The sign of the trace decides whether the spiral enters or leaves.
Drag point (τ,δ) in the left plane (it snaps to the parabola and axes) or edit A, and inspect the portrait on the right. Dashed orange and aqua lines are eigenlines with real eigenvalues. Explore half-plane δ<0 (saddles), cross the parabola from node to focus and watch trajectories stop being tangent to a line and start rotating. Cross axis τ=0 above the parabola: a stable focus passes through a center and becomes unstable. On the parabola toggle the Jordan block: how do degenerate node and star differ? Click the portrait to launch trajectories and enable particles to see flow.
Classification follows from the three forms above. If x=Py, orbits of x′=Ax are images under P of orbits of y′=P−1APy: a linear coordinate change stretches and rotates the portrait without changing qualitative type (hence the figure’s eigenlines are not perpendicular). It suffices to inspect canonical forms:
Node and saddle (A=diag(λ1,λ2)). Orbits satisfy ∣y2∣=c∣y1∣λ2/λ1. With λ1,λ2 of the same sign they are parabolic curves tangent at the origin to the slower-eigenvalue axis, with smaller ∣λ∣ (each half-axis is itself an orbit). Opposite signs make the ratio negative, producing hyperbolas with axes as asymptotes: only stable-axis orbits reach the origin.
Focus and center (C=αI+βJ). In polar coordinates r′=αr and θ′=β, hence r=r0e(α/β)(θ−θ0): logarithmic spirals. At α=0, r is constant: circles, ellipses in the original basis, level curves of a conserved quadratic form V(x)=x⊤Sx (with positive definite S).
Degenerate (Jλ). Orbits are y1=eλt(c1+c2t), y2=c2eλt: all become tangent, approaching or departing, to the sole eigenline (axis y1).
A practical planar stability criterion follows: the origin is asymptotically stable if and only if τ<0 and δ>0. For real roots product δ>0 gives the same sign and sum τ<0 makes them negative; for complex roots their real part is τ/2 and δ=α2+β2>0 is already guaranteed.
Liouville’s formula: trace measures volume
The flow figure suggested a nonobvious fact: F’s area is multiplied by ettrA, depending on A only through its trace. This is general.
Proof
By Schur form, some invertible Q gives A=QTQ−1 with upper triangular T and eigenvalues λ1,…,λn (with multiplicities) on the diagonal. Property (3) gives etA=QetTQ−1, and determinant is invariant under similarity. Powers of an upper triangular matrix remain upper triangular with diagonal λik, as does the etT series, with diagonal ∑k(tλi)k/k!=etλi. A triangular determinant is the diagonal product:
detetA=i=1∏netλi=et∑iλi=ettrA,
because trace is the eigenvalue sum.
∎
Thus detetA>0 for real A, so flow preserves orientation: the F never flips. Since etA is linear, it multiplies area (volume in dimension n) of any set by its absolute determinant: the Jacobian of change of variables x↦etAx from lesson 11. Geometrically:
vol(etAS)=ettrAvol(S).
Trace of A is also divergence of field x↦Ax because ∇⋅(Ax)=∑i∂i(Ax)i=∑iaii. This is the linear case of the general fact: field divergence is the flow’s volume-expansion rate. (Hamiltonian mechanics has zero divergence and preserves phase-space volume: Liouville’s theorem in mechanics.) If trA<0 flow contracts, if trA>0 expands, and if trA=0 preserves volume despite deformation (the figure’s rotation and shear look nothing alike yet both have zero trace). Centers in plane (τ,δ) lie at τ=0 for a deeper reason: an inward or outward spiral contracts or expands area, while a closed orbit enclosing the same region requires area-preserving flow.
A curiosity: since deteA=etrA>0 for real A, matrices such as diag(−1,1) (a reflection, determinant −1) are not the exponential of any real matrix. The formula also has a variable-coefficient version detΦ(t)=detΦ(t0)exp∫t0ttrA(s)ds, proved from Jacobi’s determinant-derivative formula in an exercise.
Systems with input: Duhamel’s formula
A real system is rarely alone: external signal u(t) pushes it (force, voltage, control action, network-layer input). The input model is
x′(t)=Ax(t)+Bu(t),x(0)=x0,
with B∈Rn×m and piecewise-continuous u. The solution is the previous lesson’s variation of constants in matrix form.
Proof
Seek x(t)=etAc(t) with c unknown. By product rule and (etA)′=AetA,
x′=AetAc+etAc′=Ax+etAc′.
For x to solve the equation we need etAc′=Bu, i.e. c′(t)=e−tABu(t). Integrating from c(0)=x0 gives c(t)=x0+∫0te−sABu(s)ds; multiplying by etA (entering the integral and using etAe−sA=e(t−s)A) yields the formula. The problem has a unique solution (Picard–Lindelöf on each interval where u is continuous, since the right side is Lipschitz in x, joining solutions at jumps of u), so this is it.
∎
Read it as superposed impulses. At each instant s, input supplies an instantaneous push Bu(s)ds, which evolves freely for remaining time t−s transported by e(t−s)A. Current state is evolved initial state plus the sum of evolved pushes.
If only linear output y=Cx is observed and x0=0, the formula says y=h∗u is convolution with impulse response
h(t)=CetAB.
This identity (a linear time-invariant system is convolution whose kernel comes from etA) allows training an SSM as a long convolution and running it as a recurrence at inference.
Discretization: from equation to recurrence
A computer handles sequences, not continuous t. Suppose input is held constant on each interval of length Δ (zero-order hold, ZOH), u(t)=uk for t∈[kΔ,(k+1)Δ). Duhamel from kΔ to (k+1)Δ gives an exact formula, not an approximation:
where the final equality requires invertible A (calculate the integral with dsdesA=AesA). For example, for x′=−x+u and Δ=0.1, Aˉ=e−0.1≈0.9048 and Bˉ=1−e−0.1≈0.09516.
There are other discretizations. For scalar mode x′=λx:
Method
aˉ
Stable for every Δ if Reλ<0?
Explicit Euler
1+Δλ
no: requires ∣1+Δλ∣<1
Implicit Euler
1−Δλ1
yes
Bilinear (Tustin, trapezoidal rule)
1−Δλ/21+Δλ/2
yes
Zero-order hold
eΔλ
yes (and exact)
The discrete recurrence is stable when eigenvalues of Aˉ have modulus below 1, not negative real part: the discrete criterion must not be confused with continuous stability. With ZOH, eigenvalues of Aˉ are eΔλi, modulus eΔReλi, mapping the left half-plane into the unit disk for everyΔ>0. Bilinear also maps it into the disk. Explicit Euler does not: for very negative real λ, ∣1+Δλ∣<1 requires Δ<2/∣λ∣ (the next lesson turns this into gradient-descent step-size condition).
State space models: memory and selectivity
Observing yk=Cxk from x0=0 unrolls the recurrence into discrete convolution,
yk=m=0∑k−1Kmuk−1−m,Km=CAˉmBˉ,
with the same kernel obtained by integrating continuous impulse response over each step: Km=∫mΔ(m+1)ΔCesABds≈Δh((m+21)Δ). Structured SSMs parameterize A with structure making kernel calculation and convolution cheap (diagonal plus low-rank correction in S4; diagonal in S4D and Mamba), and learn Δ as another parameter. Original S4 used bilinear discretization; Mamba uses ZOH, and S4D supports both. With diagonal A modes are scalar, λi, and kernel is a sum of discrete exponentials aˉim.
How long does the system remember? Mode i loses factor e−1 every m steps with eΔλim=e−1, i.e. m=1/(Δ∣λi∣)steps, or continuous time 1/∣λi∣. With pole λ=−2 and Δ=0.05 this is 10 steps; with Δ=1 it is 0.5 and each token erases almost everything before it. Memory in steps is set by product Δ∣λ∣: a pole near zero or small step gives long memory.
InteractiveDiscretizing a state space model
Impulse response: continuous versus discrete
Discrete poles eΔλ in the z plane
continuous response h(t)=CetAB
exact discrete (zero-order hold), Km/Δ
View
Poles
∣aˉ∣=e−Δa (slow pole)0.8869
Memory in steps 1/(Δa)8.3
Memory in time 1/a3.3
Steps in window [0,12]30
In Kernel view, a system with two real poles (or a complex pair) is discretized by zero-order hold. Points are discrete kernel Km/Δ, gray curve continuous response h(t), and right are discrete poles eΔλ against the unit circle. Lower Δ until points and curve coincide; increase it to see memory in steps shorten and discrete poles approach 0. Enable bilinear method (hollow circles), and with both poles fast and large Δ see discrete poles become negative and kernel alternate signs. Selectivity view has one pole and one key token among noise: with Δ equal for all tokens the system forgets the key, while small Δ on noise preserves it.
Selectivity view shows Mamba’s central mechanism. In an invariant SSM (S4), Δ, B and C do not depend on input and the whole system is convolution. In Mamba, Δt, Bt and Ct are functions of token xt (typically Δt=softplus(Wxt+b)), making recurrence ht=eΔtAht−1+Bˉtxttime-varying. With diagonal, negative-real-part A:
If Δt is large, eΔtA≈0 and Bˉt reaches its maximum −A−1B: state resets and only current token matters.
If Δt is small, eΔtA≈I and Bˉt≈0: state is preserved and token ignored.
The model learns to modulate Δt as a gate (like a GRU’s). The cost of selectivity is losing convolution: no single kernel remains, so recurrence is computed with an associative parallel scan. Those details belong to sequence architectures; here we need the mathematics of Δ. In its reference implementation Mamba retains eΔA for Aˉ but simplifies Bˉ≈ΔB (first-order Euler value).
Implementation from scratch
The series defines eA but is not a good algorithm. Compare three approaches:
Truncated series: sum ∑k<KAk/k!. Theoretically exact, it fails in practice for large ∥A∥: terms grow to ∥A∥k/k! (maximum of order e∥A∥) before decaying, and when the answer is much smaller than the maximum (e.g. e−30) it is lost to cancellation.
Diagonalization: VeΛV−1. It works only if A is diagonalizable, and if nearly defective V is ill-conditioned and error is multiplied by κ(V).
Scaling and squaring. Property (1) gives eA=(eA/2s)2s. Scaling and squaring chooses s so ∥A∥/2s≤21, computes eA/2s with a short Taylor series (for ∥B∥≤21, terms through B16/16! leave truncation error below 3⋅10−20, far below rounding), and squares the result s times. Libraries use this method with Padé approximants instead of Taylor.
[ ]The matrix exponential three waysBrowser
import numpy as np
from scipy.linalg import expm
def expm_serie(A, terminos=80):
"""Suma directa de la serie de Taylor."""
n = A.shape[0]
S, T = np.eye(n), np.eye(n)
for k in range(1, terminos):
T = T @ A / k # T = A^k / k!
S = S + T
return S
def expm_diag(A):
"""V diag(e^w) V^-1: solo para A diagonalizable."""
w, V = np.linalg.eig(A)
E = V @ np.diag(np.exp(w)) @ np.linalg.inv(V)
return E.real if np.isrealobj(A) else E
def expm_ss(A, grado=18):
"""Escalado y cuadrado: Taylor de A / 2^s y s cuadrados."""
nrm = np.linalg.norm(A, 1)
s = max(0, int(np.ceil(np.log2(nrm / 0.5)))) if nrm > 0.5 else 0
B = A / 2**s
S, T = np.eye(A.shape[0]), np.eye(A.shape[0])
for k in range(1, grado + 1):
T = T @ B / k
S = S + T
for _ in range(s):
S = S @ S
return S
rng = np.random.default_rng(1)
M = rng.normal(size=(6, 6)); M *= 50 / np.linalg.norm(M, 2)
casos = {
"rotación (ω = 3)": np.array([[0.0, -3.0], [3.0, 0.0]]),
"defectiva [[−2, 1], [0, −2]]": np.array([[-2.0, 1.0], [0.0, -2.0]]),
"no normal, autovalores −30 y −25": np.array([[-30.0, 20.0], [0.0, -25.0]]),
"aleatoria 6×6 con ‖A‖₂ = 50": M,
}
print(f"{'caso':34s} {'serie':>10s} {'diagonal':>10s} {'esc.-cuad.':>10s}")
for nombre, A in casos.items():
ref = expm(A)
err = lambda E: np.linalg.norm(E - ref) / np.linalg.norm(ref)
print(f"{nombre:34s} {err(expm_serie(A)):10.1e} {err(expm_diag(A)):10.1e} {err(expm_ss(A)):10.1e}")
# la cancelación a la vista: e^{-30} sumando su serie
s, t = 0.0, 1.0
for k in range(1, 400):
s, t = s + t, t * (-30) / k
print(f"\nserie de e^(-30): {s:.3e} exacto: {np.exp(-30):.3e} término máximo: {30**30 / 2.65e32:.1e}")
All three methods correctly handle rotation, which is normal and moderate. The defective case breaks diagonalization: eig returns nearly singular V and relative error 0.58, meaning no correct digits. With eigenvalues −30 and −25 the opposite occurs: diagonalization succeeds (two distinct eigenvalues) and direct series loses everything because terms reach 1012 while the result is order 10−11 and relative error 1010. Scaling and squaring succeeds on all four with errors between 10−15 and 10−14.
A short cell checks two numerical consequences of Liouville’s formula and noncommutativity.
[ ]Liouville and noncommutativityBrowser
import numpy as np
from scipy.linalg import expm
rng = np.random.default_rng(3)
A = rng.normal(size=(5, 5))
print("det e^A =", np.linalg.det(expm(A)), " e^tr(A) =", np.exp(np.trace(A)))
N = np.array([[0.0, 1.0], [0.0, 0.0]]) # N y su traspuesta no conmutan
print("N N^T - N^T N =\n", N @ N.T - N.T @ N)
print("e^N e^(N^T) =\n", expm(N) @ expm(N.T))
print("e^(N+N^T) =\n", expm(N + N.T))
Determinant of eA agrees with etrA up to rounding even for unstructured A. And eNeN⊤ is [2111] versus [1.5431.1751.1751.543] for eN+N⊤: they differ.
Now Duhamel. A forced damped oscillator y′′+0.4y′+4y=cos1.5t is solved three ways: Duhamel integral (trapezoidal quadrature and e(t−s)A from the prior cell), solve_ivp, and exact zero-order-hold recurrence.
[ ]Duhamel versus solve_ivpBrowser
import numpy as np
from scipy.linalg import expm
from scipy.integrate import solve_ivp
A = np.array([[0.0, 1.0], [-4.0, -0.4]])
B = np.array([0.0, 1.0])
x0 = np.array([1.0, 0.0])
u = lambda t: np.cos(1.5 * t)
T = 6.0
# 1) Duhamel: x(T) = e^{TA} x0 + ∫ e^{(T-s)A} B u(s) ds (trapecios)
s = np.linspace(0.0, T, 2001)
integrando = np.array([expm((T - si) * A) @ B * u(si) for si in s])
trapecios = ((integrando[1:] + integrando[:-1]) / 2 * np.diff(s)[:, None]).sum(axis=0)
x_duhamel = expm(T * A) @ x0 + trapecios
# 2) integrador numérico de alta precisión
sol = solve_ivp(lambda t, x: A @ x + B * u(t), (0, T), x0, rtol=1e-11, atol=1e-13)
x_ivp = sol.y[:, -1]
# 3) ZOH exacto con entrada constante a trozos: la comparamos con una entrada también constante a trozos
dt = 0.05
Abar = expm(dt * A)
Bbar = np.linalg.solve(A, Abar - np.eye(2)) @ B
uk = u(np.arange(int(round(T / dt))) * dt) # u se mantiene en cada intervalo
x, y = x0.copy(), x0.copy()
for k in range(len(uk)):
x = Abar @ x + Bbar * uk[k] # la recurrencia exacta
sol_k = solve_ivp(lambda t, z: A @ z + B * uk[k], (0, dt), y, rtol=1e-12, atol=1e-14)
y = sol_k.y[:, -1] # integrar cada intervalo con u constante
print("Duhamel (trapecios) :", x_duhamel, " error", np.linalg.norm(x_duhamel - x_ivp))
print("solve_ivp :", x_ivp)
print("recurrencia ZOH :", x, " frente a integrar con u constante a trozos:", np.linalg.norm(x - y))
First error is quadrature error (second order in step, order 10−6 with 2000 intervals). The third is rounding: with piecewise-constant u the recurrence is exact, not approximate, and its difference from solve_ivp interval integration is the integrator tolerance size.
With libraries
scipy.linalg.expm uses scaling and squaring with Padé approximants whose degree and scaling depend on norm of A (Al-Mohy and Higham, 2009). Moler and Van Loan’s classic Nineteen dubious ways to compute the exponential of a matrix (1978, revised 2003) explains why other methods are less reliable. For discretization, scipy.signal.cont2discrete implements ZOH, bilinear and others; PyTorch provides torch.linalg.matrix_exp with automatic differentiation.
[ ]cont2discrete versus the exact formulaBrowser
import numpy as np
from scipy.linalg import expm
from scipy.signal import cont2discrete
# SSM diagonal con tres polos reales estables
lam = np.array([-0.5, -2.0, -8.0])
A, B = np.diag(lam), np.ones((3, 1))
C, D = np.array([[1.0, 1.0, 1.0]]) / 3, np.zeros((1, 1))
dt = 0.1
Ad, Bd, Cd, Dd, _ = cont2discrete((A, B, C, D), dt, method="zoh")
Ab = expm(dt * A)
Bb = np.linalg.solve(A, Ab - np.eye(3)) @ B
print("ZOH |Ā − Ā_scipy| =", np.abs(Ad - Ab).max(), " |B̄ − B̄_scipy| =", np.abs(Bd - Bb).max())
print("B̄ diagonal exacta:", Bb.ravel(), " = (e^{Δλ} − 1)/λ:", (np.exp(dt * lam) - 1) / lam)
Ai, Bi, *_ = cont2discrete((A, B, C, D), dt, method="bilinear")
print("polos discretos ZOH :", np.diag(Ab))
print("polos discretos bilineal :", np.diag(Ai))
# el núcleo K_m = C Ā^m B̄ y la salida como convolución
n = 60
K = np.array([(Cd @ np.linalg.matrix_power(Ad, m) @ Bd).item() for m in range(n)])
u = np.random.default_rng(0).normal(size=n)
y_conv = np.array([sum(K[m] * u[k - 1 - m] for m in range(k)) for k in range(n)])
x, y_rec = np.zeros((3, 1)), []
for k in range(n):
y_rec.append((Cd @ x).item())
x = Ad @ x + Bd * u[k]
print("convolución frente a recurrencia:", np.abs(y_conv - np.array(y_rec)).max())
print("memoria del modo lento: 1/(Δ|λ|) =", 1 / (dt * 0.5), "pasos")
Recurrence and convolution give the same output up to rounding, which S4 exploits: process a long sequence in one convolution and generate token by token using recurrence without changing the model. In PyTorch:
import torchA = torch.tensor([[0.0, 1.0], [-4.0, -0.4]], requires_grad=True)E = torch.linalg.matrix_exp(0.05 * A) # diferenciable: pasa gradiente a AE.trace().backward() # d tr(e^{ΔA}) / dA
Common mistakes
Exercises
NumericThe determinant of e^A
A matrix A∈R3×3 has trace 3. Calculate det(eA).
QuizClassify the origin
Classify the origin of x′=Ax for these four matrices in order: A1=[1−221], A2=[−100−3], A3=[0−410], A4=[200−1].
ProofDerivative of e^{tA} from the series
Prove: For A∈Rn×n, dtdetA=AetA, by termwise differentiation.
0
Fix T>0 and work on [−T,T] with a submultiplicative norm. Let SN(t)=∑k=0NtkAk/k!.
Step 1 of 4. Which lesson 14 theorem permits termwise differentiation of the limit of SN?
NumericExact discretization of a mode
Discretize system x′=−x+u by zero-order hold with step Δ=0.1. Calculate Bˉ in xk+1=Aˉxk+Bˉuk.
ProofLiouville from Jacobi’s formula
Prove: Let X(t)=etA. Prove detX(t)=ettrA using Jacobi’s formula dtddetX(t)=detX(t)tr(X(t)−1X′(t)) for invertible differentiable X(t).
0
Let w(t)=detX(t). You know X(0)=I and X′(t)=AX(t).
Step 1 of 2. What equation does w satisfy?
NumericDuhamel with exponential input
Solve x′=−2x+e−t with x(0)=0 using Duhamel and give x(1).
NumericWhen they do not commute
Let N=[0010]. Calculate tr(eN+N⊤).
QuizStability after discretization
Mode x′=λx with λ=−50 is stable. Discretize with Δ=0.1. Which methods give stable recurrence xk+1=aˉxk (∣aˉ∣<1)?
More than one answer may be correct.
NumericMemory of a discretized pole
A mode with pole λ=−2 is discretized by ZOH at step Δ=0.05. How many steps until response decreases by factor e (to e−1)?
CodeMatrix exponential by scaling and squaring
Implement expm_scaling_squaring(A) returning eA by scaling and squaring: choose minimum s≥0 with ∥A∥1/2s≤0.5, sum the Taylor series of A/2s with 18 terms, and square the result s times. Do not use scipy.linalg.expm or np.linalg.eig. It must work for matrices of any size, A = 0 and very large norm.
import numpy as np
def expm_scaling_squaring(A):
"""Exponencial de matriz por escalado y cuadrado (Taylor de grado 18)."""
A = np.asarray(A, dtype=float)
# tu código: s mínimo con ||A||_1 / 2**s <= 0.5, serie de B = A / 2**s, y s cuadrados
return np.eye(A.shape[0])
Shift+Enter to run
Summary
Key idea
Linear system x′=Ax is solved by matrix exponential x(t)=etAx0, and eigenvalues of A determine behavior: for 2×2 trace and determinant give the entire phase portrait, while trace also measures volume expansion.
Exponential eA=∑Ak/k! always converges, satisfies dtdetA=AetA and uniquely solves the problem. Equality eA+B=eAeB holds only if A and B commute.
Jordan form computes it: PetΛP−1 in the diagonalizable case, eαt by rotation for complex eigenvalues α±iβ, and polynomial factor tkeλt for defective blocks. The origin is asymptotically stable iff all eigenvalues have Reλ<0.
In the plane, portrait (saddle, node, focus, center and boundary cases) is read from (τ,δ) and parabola τ2=4δ. Centers and parabola cases are fragile.
Liouville: detetA=ettrA. Trace is field divergence and measures volume expansion: zero trace preserves area.
With input, x(t)=etAx0+∫0te(t−s)ABu(s)ds (Duhamel), and output is convolution with CetAB. Zero-order hold gives exact recurrence Aˉ=eΔA, Bˉ=A−1(eΔA−I)B.
A mode’s memory is 1/(Δ∣λ∣) steps; making Δ input-dependent is Mamba’s selectivity mechanism. Continuous stability (Reλ<0) differs from discrete (λˉ<1).
Numerically use scaling and squaring (or Padé) via scipy.linalg.expm: direct series and nearly defective diagonalization are unreliable.