Diagonalization, matrix functions and linear dynamics
Diagonalization chooses a basis where a matrix acts coordinate by coordinate, enabling powers, exponentials and other matrix functions. Study discrete and continuous linear systems, spectral-radius stability and its limits for nonnormal matrices, and Jordan form for defective matrices. This underlies state-space models.
After this lesson you can
Diagonalize a matrix when possible and use A = VΛV⁻¹ to calculate Aᵏ and f(A).
Solve linear recurrences in closed form and predict their asymptotic behavior.
Determine stability of xₖ₊₁ = Axₖ and x' = Ax from eigenvalues.
Compute a matrix exponential and use it to discretize a continuous system exactly.
Recognize transient growth of nonnormal matrices and the role of Jordan form.
Many systems you will build have a state evolving by repeatedly applying the same matrix. Such a model is a linear dynamical system: in discrete time,
xk+1=Axk+Buk,
and in continuous time, x′(t)=Ax(t)+Bu(t), with state x∈Rn, transition matrix A∈Rn×n and external input u, often zero (an autonomous system). They appear in many settings:
Linear recurrent networks and state-space models. An SSM layer stores state ht=Aht−1+Bxt and emits yt=Cht. Unrolling gives ht=∑s≤tAt−sBxs: what the model remembers of a token k steps ago is multiplied by Ak. If Ak explodes, gradients explode; if it quickly vanishes, the model forgets (see exploding and vanishing gradients). State-space models such as S4 and Mamba start with a continuous system and discretize it using a matrix exponential, constructed here.
Momentum. The heavy-ball method on a quadratic is a linear system in pair (wk,wk−1); its convergence rate is the magnitude of eigenvalues of a matrix 2×2 (see stability below and momentum).
Markov chains, populations and time series. A chain’s distribution advances as πk+1⊤=πk⊤P; a VAR model’s stationarity depends on its matrix eigenvalues (VAR stability).
Physics and control. A damped oscillator, circuit, or robot linearized around equilibrium is x′=Ax.
The shared question: what is xk=Akx0 for large k without computing k products? Does it tend to zero, escape, oscillate? In continuous time, what is x(t)? One idea answers: find a basis in which A does not mix coordinates. There, applying A a thousand times raises n numbers to the thousandth power; any matrix function (square root, logarithm, exponential) applies the scalar function to those n numbers.
Diagonalization: the basis where the matrix does not mix
In the previous lesson an eigenvector is a direction A only scales: Av=λv. Suppose you have n eigenvectors v1,…,vn with eigenvalues λ1,…,λn and place them in columns of V. The n equalities Avj=λjvj are one matrix equality, column by column:
If the eigenvectors are also linearly independent, V is invertible and we can solve for A.
Read the factorization right to left as three steps applied to vector x. First c=V−1x are coordinates of x in the eigenvector basis: x=c1v1+⋯+cnvn. Then Λ multiplies each coordinate by its eigenvalue, without mixing coordinates. Finally V reconstructs the vector in the standard basis. In change-of-basis language, Λ is the same map’s matrix in the eigenvector basis, and A and Λ are similar. Diagonalization chooses a basis where the map is as simple as possible: n independent scalings.
This is the matrix in the first interactive. On the left are iterations xk=Akx0 in the standard basis with the deformed eigenvector-coordinate grid; on the right are the same iterations in those coordinates.
InteractiveThe diagonalization lens
Why is repeatedly applying A trivial in the eigenvector basis? Press play. On the left the trajectory first approaches the origin, then bends and escapes along v1; on the right, in coordinates c=V−1x, each step multiplies c1 by λ1=1.2 and c2 by λ2=0.6 without mixing: the orange arrow grows and aqua one shrinks. Drag x0 onto a dashed line: the trajectory no longer bends. Make λ2 negative to see jumps across the line of v1.
When does it exist?
The definition says what diagonalization is, not when it exists. The construction provides the answer:
Equivalence of 1 and 2 is the calculation above read both ways; you will prove it step by step in the exercises. Item 3 uses multiplicities: eigenvectors of distinct eigenvalues are independent, so combining eigenspace bases gives an independent set of ∑λdimnull(A−λI) vectors. Geometric multiplicity never exceeds algebraic, and algebraic multiplicities sum to n, so n is reached exactly when they agree for each eigenvalue. With n distinct eigenvalues all multiplicities are 1 automatically.
The canonical counterexample is shear S=[1011]. Its only eigenvalue is double λ=1, but S−I=[0010] has a one-dimensional null space: only one eigenvector line, axis x1, insufficient for a basis. Such matrices are defective; we return to them later.
Complex eigenvalues and real form
A rotation Rθ with 0<θ<π fixes no real line and has no real eigenvectors. It does have them over C2: eigenvalues e±iθ are distinct, so Rθ is diagonalizable over C. Everything below works equally with complex V and Λ.
If A is real and λ=a+bi (with b=0) is an eigenvalue with eigenvector v=p+iq, conjugate λˉ is also an eigenvalue with eigenvector vˉ (see complex eigenvalues). Separating real and imaginary parts of A(p+iq)=(a+bi)(p+iq) gives Ap=ap−bq and Aq=bp+aq. In real basis P=[qp],
A=P[ab−ba]P−1=P(rRθ)P−1,r=∣λ∣,θ=argλ.
This is real canonical form: in a suitable basis a complex eigenvalue pair corresponds to rotation by θ followed by scaling by r. A real 2×2 matrix with complex eigenvalues rotates (in an oblique basis) and scales; that is its entire dynamics.
Powers: the dominant eigenvalue governs
Diagonalization turns matrix powers into powers of numbers. Interior factors cancel:
This formula compresses the whole lesson. The state is a sum of modes: each is a fixed direction vi with weight evolving as geometric progression ciλik. Modes do not interact. In the example, (Ak)11=(2⋅1.2k+0.6k)/3 without a single matrix multiplication.
Order eigenvalues by magnitude and suppose one is strictly dominant, ∣λ1∣>∣λ2∣≥⋯, and c1=0. Factoring gives
xk=λ1k(c1v1+i≥2∑ci(λ1λi)kvi).
Ratios ∣λi/λ1∣<1 make the sum vanish: the direction of xk converges to that of v1, with error of order ∣λ2/λ1∣k, and size grows or decays as ∣λ1∣k. This is the principle of power iteration and PageRank: repeated multiplication extracts the dominant eigenvector, faster with a larger spectral gap.
Fibonacci in closed form
Recurrence Fk+2=Fk+1+Fk, with F0=0 and F1=1, is a two-dimensional linear system if the last two terms are stored:
The characteristic polynomial of F is λ2−λ−1, with roots φ=(1+5)/2≈1.618 (the golden ratio) and ψ=(1−5)/2≈−0.618. Since F−λI=[1−λ11−λ] and λ2=λ+1, vector (λ,1) lies in its null space: eigenvectors are v1=(φ,1) and v2=(ψ,1). Write the initial state in that basis: (1,0)=c1(φ,1)+c2(ψ,1) requires c1+c2=0 and c1φ+c2ψ=1, hence c1=−c2=1/(φ−ψ)=1/5. The second coordinate of xk=c1φkv1+c2ψkv2 is Binet’s formula:
Fk=5φk−ψk.
Two immediate consequences. Since ψk/5<1/2 for every k≥0, Fk is the integer nearest φk/5: the dominant mode suffices. Ratio Fk+1/Fk tends to φ with error proportional to (∣ψ∣/φ)k=φ−2k≈0.382k: each step gains a factor 2.6 in accuracy.
InteractiveFibonacci and the golden ratio
Where does Binet's formula come from? Return to k=0 and play: the direction of xk=(Fk+1,Fk) alternates around and approaches the eigenvector line of φ (the sign of ψk alternates). The table splits each Fk into two modes: orange grows as φk, aqua alternates and shrinks, always below 1/2. Below, ratio error falls in a straight line on a log scale at the predicted slope ∣ψ∣/φ. Choose ‘Free’ and drag x0 nearly onto the line of ψ: with c1≈0 convergence takes much longer to begin.
The same method solves any linear recurrence of order d, ak+d=αd−1ak+d−1+⋯+α0ak: stack the last d terms in a vector to obtain a system with a companion matrix, whose characteristic polynomial is the recurrence’s. If roots r1,…,rd are distinct, the matrix is diagonalizable and ak=∑iβirik. With repeated roots the companion matrix is not diagonalizable and terms krk appear; Jordan form later explains why.
Discrete dynamics: the phase plane
With n=2 we can see all dynamics of xk+1=Axk in the plane. The mode formula says everything depends on the two eigenvalues’ positions relative to unit circle ∣λ∣=1:
Eigenvalues
Name
Trajectory behavior
real, ∣λ1∣,∣λ2∣<1
stable node
approach 0; eventually tangent to the line of the greatest-magnitude eigenvalue (slow mode)
real, one inside and one outside
saddle
escape except those starting exactly on the line of the eigenvalue with magnitude below 1
real, both outside
source
all escape except 0
some λ<0
(any of the above)
that component changes sign each step: jumps between sides
complex re±iθ, r<1
stable spiral
rotate θ per step (in basis P) and shrink by r
complex, r>1
unstable spiral
rotate and grow
complex, r=1
center
trace fixed ellipses, neither inward nor outward
InteractiveDiscrete phase plane
What decides whether xk+1=Axk tends to zero, escapes or rotates? Drag eigenvalues in the side panel (in ‘Complex’ mode conjugate λˉ follows) and click the plane to launch trajectories. Move λ1 outside the circle and the node becomes a saddle: only the aqua line survives. Move an eigenvalue to the negative axis and trajectories jump sides. In complex mode cross the unit circle and the spiral changes from inward to outward (rotation direction stays the same); on the circle points follow gray ellipses.
Spectral radius and stability
The table suggests that convergence to zero depends only on the largest-magnitude eigenvalue.
Proof
If ρ(A)≥1, an eigenvalue ∣λ∣≥1 has eigenvector v=0, and Akv=∣λ∣k∥v∥≥∥v∥ does not tend to zero.
Conversely suppose ρ(A)<1 and, for now, diagonalizable A=VΛV−1. Use the Euclidean norm and its induced matrix norm ∥M∥2=maxx=0∥Mx∥2/∥x∥2, which is submultiplicative. Since Λk2=maxi∣λi∣k=ρk,
Ak2=VΛkV−12≤∥V∥2V−12ρ(A)k=κ(V)ρ(A)k⟶0.
The non-diagonalizable case follows from Jordan form later (and is the second proof exercise).
∎
The proof’s bound contains a factor to watch: the condition numberκ(V)=∥V∥V−1 of the eigenvector matrix. It guarantees Ak eventually decays as ρk, but not that it decays immediately. There is also an exact asymptotic characterization, Gelfand’s formula: ρ(A)=limk→∞Ak1/k for any matrix norm. Spectral radius describes the long-term rate, saying little about initial steps.
Stable, but with a surprise
Take A=Vdiag(0.9,0.8)V−1 with nearly parallel eigenvectors v1=(1,0) and v2=(cosθ,sinθ). Spectral radius 0.9 makes the system stable. But a vector like x0=(0,1), nearly perpendicular to both, requires huge nearly opposite coefficients in that basis: x0=c1v1+c2v2 with c2=1/sinθ and c1=−cosθ/sinθ. Initially they cancel; since they decay at different rates (0.9k versus 0.8k), cancellation stops and xk grows substantially before both die away. With θ=2°, Ak2 reaches 7.7 at k=6 and only falls below 1 at k=32; with θ=0.5°, at 31.
InteractiveStable, but with a surprise
If ρ(A)<1, can Akx grow before decaying? The magenta curve is Ak2, worst possible amplification in k steps; blue is for your x0. Close angle θ: the peak rises like κ(V) even though ρ=0.9 is unchanged, and the curve stays between ρk (the eventual rate) and bound κ(V)ρk. Press ‘Worst initial direction’ to select the x0 attaining the peak. Open θ to 90° (orthogonal eigenvectors) and the surprise disappears.
This is transient growth in nonnormal matrices. A matrix is normal if AA∗=A∗A; normal matrices are exactly those diagonalizable with orthonormal eigenvectors (real symmetric matrices are studied with the spectral theorem). For them κ(V)=1 and Ak2=ρ(A)k exactly: no surprise. Otherwise spectral intuition and actual behavior may differ by orders of magnitude; Trefethen and Embree’s book in the sources measures this.
Matrix functions
If Ak=VΛkV−1, summing powers with coefficients gives, for any polynomial p(z)=∑jajzj,
A polynomial acts on a diagonalizable matrix by acting on each eigenvalue. Generalization is immediate.
Check that it is independent of the chosen V (eigenvectors can be scaled, and any basis chosen inside an eigenspace of dimension above 1). Interpolation is the trick: if μ1,…,μm are the distinct eigenvalues, there is a polynomial p (Lagrange’s, of degree less than m) with p(μj)=f(μj). Then f(Λ)=p(Λ) and f(A)=Vp(Λ)V−1=p(A), depending only on A. Three useful properties follow: f(A) commutes with A (it is a polynomial in A), every eigenvector vi of A is one of f(A), and its eigenvalues are f(λi). (There may be more eigenvectors: if f takes the same value at two distinct eigenvalues, eigenspaces merge.) With f equal to characteristic polynomial pA, zero at all eigenvalues, obtain pA(A)=0: Cayley–Hamilton for diagonalizable matrices (it holds for all).
Square root. For the example matrix A=Vdiag(1.2,0.6)V−1≈[0.98850.10690.21390.8815], squaring gives A. If A advances the system “half a step”, At=VΛtV−1 (with positive eigenvalues) interpolates the discrete trajectory at noninteger times. With n distinct nonzero eigenvalues there are exactly 2n square roots, one per sign choice; the principal root takes the root with positive real part for each eigenvalue and exists uniquely if no eigenvalue lies in (−∞,0]. Positive definite matrices have a symmetric principal square root used throughout. Beware repeated eigenvalues: identity I2 has infinitely many square roots, because any reflection H satisfies H2=I, and only ±I are polynomials in I (the rest cannot be obtained with formula Vf(Λ)V−1).
Logarithm.logA=Vdiag(logλi)V−1 requires nonzero eigenvalues, and for the real principal logarithm none in (−∞,0). For a rotation, logRθ=θ[01−10] if ∣θ∣<π. The logarithm inverts the exponential below and answers a practical question: if a system is observed every Δt seconds and A estimated, which continuous system generated it? The answer is log(A)/Δt, with an ambiguity seen shortly.
The matrix exponential
The most important matrix function is defined without diagonalization by the same power series as the scalar exponential.
The series converges for every A: with a submultiplicative norm Ak/k!≤∥A∥k/k!, and ∑k∥A∥k/k!=e∥A∥ is finite, so convergence is absolute (and uniform on ∥A∥≤R). If A=VΛV−1, summing term by term recovers the general definition: eA=Vdiag(eλ1,…,eλn)V−1.
Proof
(1) Both series converge absolutely, so their product can be rearranged (Cauchy product): eAeB=∑m∑j+k=mj!k!AjBk=∑mm!1∑j=0m(jm)AjBm−j. If A and B commute, the binomial theorem applies to matrices and the inner sum is (A+B)m. Without commutation, (A+B)2=A2+AB+BA+B2=A2+2AB+B2 and the argument fails.
(2) sA and tA commute; apply (1). With s=−t obtain etAe−tA=e0=I.
(3) Series ∑ktkAk/k! is a power series in t with infinite convergence radius, differentiated term by term: ∑k≥1tk−1Ak/(k−1)!=AetA, and factor A may come out on either side.
(4) (SAS−1)k=SAkS−1 term by term.
(5) If A is diagonalizable, deteA=∏ieλi=e∑iλi=etrA (trace is the sum of eigenvalues, as seen). Diagonalizable matrices are dense (arbitrarily small perturbations separate eigenvalues) and both sides are continuous in A, so the identity holds for every matrix.
∎
The assumption in (1) matters. With A=[0010] and B=[0100], both nilpotent (A2=B2=0), the series terminate and eA=I+A, eB=I+B:
The discrepancy is measured by commutator [A,B]=AB−BA: Baker–Campbell–Hausdorff gives etAetB=et(A+B)+2t2[A,B]+O(t3). Splitting methods, taking one step with A and another with B, therefore incur error of order t2 per step.
Solving x′=Ax
Property 3 says x(t)=etAx0 satisfies x′=Ax and x(0)=x0. It is unique: if y is another, dtd(e−tAy(t))=e−tA(y′−Ay)=0, so e−tAy(t) is constant and equal to x0. (This is the simplest case of linear ODE systems.) If A is diagonalizable, the solution is again a sum of modes:
x(t)=c1eλ1tv1+⋯+cneλntvn,eλt=eRe(λ)t.
Each mode’s size depends only on the eigenvalue’s real part; the imaginary part causes rotation. The stability boundary changes from the unit circle to the imaginary axis: etA→0 if and only if Reλ<0 for every eigenvalue.
Exact discretization
Observing the continuous system every Δt, property 2 gives a discrete system without error:
xk+1=x((k+1)Δt)=eΔtAx(kΔt)=Aˉxk,Aˉ=eΔtA.
Eigenvalues of Aˉ are μ=eΔtλ, with ∣μ∣=eΔtReλ. The exponential maps left half-plane Reλ<0 inside the unit disk and the imaginary axis to its boundary: exact discretization preserves stability for any step size. Explicit Euler truncates the series after its first term, xk+1=(I+ΔtA)xk, with eigenvalues 1+Δtλ; it is stable only if ∣1+Δtλ∣<1, a disk centered at −1/Δt with radius 1/Δt in plane λ. For a frictionless oscillator λ=±iω and ∣1+iωΔt∣=1+ω2Δt2>1 for every step: Euler always injects energy.
InteractiveContinuous flow and exact discretization
What decides stability of x′=Ax, and how can it be discretized without breaking it? The system is oscillator x′′=(λ1+λ2)x′−λ1λ2x in the (position, velocity) plane. Drag eigenvalues in the λ plane: the boundary is now the imaginary axis. Blue points (eΔtA)kx0 land exactly on the continuous curve for any Δt; red Euler points escape when 1+Δtλ leaves the unit disk (with initial damping, at Δt>0.198). In the μ plane the gray grid is the left half-plane's image under λ↦eΔtλ: vertical lines become circles, horizontal lines rays.
With input u, variation of constants also gives exact discretization when input is constant within each interval, called zero-order hold (ZOH):
dtd(e−tAx(t))=e−tABu(t)
Product rule and property 3 leave e−tA(x′−Ax), with x′=Ax+Bu.
1/5
This is literally the discretization used in selective state-space models such as Mamba (Gu and Dao, 2023), applied with diagonal A so eΔtA are n scalar exponentials; S4 (Gu et al., 2021) used the bilinear transform, another discretization mapping the left half-plane to the disk. Again diagonalization makes computation cheap; see SSM discretization.
Defective matrices and Jordan form
The postponed case remains. The model non-diagonalizable matrix is the Jordan block
Jm(λ)=λ1λ⋱⋱1λ=λI+N,Nm=0,
with one eigenvalue λ of algebraic multiplicity m and one eigenvector e1. The central result says every matrix is built from these pieces.
We will not prove it (construction with generalized-eigenvector chains appears in advanced linear algebra texts). What you do need are its powers and exponential. Since λI and N commute, the binomial theorem applies and the series terminates at Nm−1:
Jk=j=0∑m−1(jk)λk−jNj,etJ=eλtj=0∑m−1j!tjNj.
For m=2:
Jk=[λk0kλk−1λk],etJ=[eλt0teλteλt].
Polynomial factors kλk−1 and teλt appear. The critically damped oscillator x′′+2x′+x=0, with double eigenvalue −1, has solutions (a+bt)e−t for this reason, and recurrences with repeated roots have terms krk. The stability theorem now holds for all matrices: each entry of Ak=PJkP−1 combines terms (jk)λk−j with j<m, and if ∣λ∣<1, polynomial (jk)≤kj loses to geometric decay. At the boundary the distinction matters: with ∣λ∣=1 and a size-2 block, Jk grows as k (marginal instability), while size-1 blocks remain bounded.
Why Jordan form is theoretical
Jordan form is discontinuous. Matrix Aε=[λε1λ] has eigenvalues λ±ε: for every ε>0 they are distinct and Aε is diagonalizable, whereas at ε=0 it is a Jordan block. Three consequences become visible in the interactive:
Eigenvalue sensitivity. A perturbation of size ε in one entry moves eigenvalues ε: with ε=10−16 (double-precision roundoff scale), 10−8. For a block of size m, the order is ε1/m.
Nearly parallel eigenvectors. Eigenvectors are (1,±ε), and κ(V) grows as 1/ε. Computing Ak or f(A) as Vf(Λ)V−1 loses the corresponding digits.
Powers do not reveal this.Aεk is nearly identical to Jk: system behavior does not change, only its spectral description becomes fragile.
InteractiveNear Jordan form
What happens to diagonalization near a defective matrix? Decrease ε and follow the vertical line: eigenvalue separation (blue) is 2ε, much larger than perturbation (gray), and κ(V) (orange) grows like 1/ε. Error in computing A20 by diagonalization (magenta) rises toward u/ε, with u≈1.1⋅10−16. Below, entry (1,2) of Aεk, equal to ((λ+ε)k−(λ−ε)k)/(2ε), nearly matches the Jordan block's kλk−1: enable ε=0 for an exact match, though V no longer exists. Raise ε to 10−1 to see the approximation holds only while kε is small.
Since rounding turns nearly any defective matrix into a diagonalizable one with ill-conditioned V, Jordan form is not computed in floating point: it is inherently unstable. Libraries use Schur decomposition, A=QTQ∗ with Qunitary and T upper triangular, which exists for every matrix and is computed stably by unitary transformations (see eigenvalues on a computer). Jordan form supports reasoning (which terms appear, why factors tjeλt arise), not computation.
Implementation from scratch
First, diagonalization and powers. np.linalg.eig returns eigenvalues and V with unit eigenvectors in columns; V * lam**k multiplies column j by λjk, giving VΛk without constructing the diagonal.
[ ]Powers by diagonalization and squaringBrowser
import numpy as np
def diagonalizar(A):
"""Devuelve (lam, V, V^{-1}) con A = V diag(lam) V^{-1}."""
lam, V = np.linalg.eig(A)
return lam, V, np.linalg.inv(V)
def potencia_diag(A, k):
lam, V, Vinv = diagonalizar(A)
return (V * lam**k) @ Vinv # V diag(lam^k) V^{-1}
def potencia_cuadrados(A, k):
"""A^k con O(log k) productos: exponenciación binaria."""
R = np.eye(A.shape[0], dtype=A.dtype)
B = A.copy()
while k > 0:
if k & 1:
R = R @ B
B = B @ B
k >>= 1
return R
A = np.array([[1.0, 0.4], [0.2, 0.8]])
lam, V, Vinv = diagonalizar(A)
print("autovalores:", lam.real)
print("A^10 diagonalizando:\n", potencia_diag(A, 10).real)
print("A^10 por cuadrados:\n", potencia_cuadrados(A, 10))
print("fórmula (2·1.2^10 + 0.6^10)/3 =", (2 * 1.2**10 + 0.6**10) / 3)
If eig detects complex eigenvalues it returns complex arithmetic throughout; here they are real, but use .real just in case, since the imaginary part of real Ak can only be rounding. Now Fibonacci: the floating-point closed form versus matrix powers with Python exact integers (dtype=object), which never round.
[ ]Fibonacci: Binet versus exact powersBrowser
phi, psi = (1 + 5**0.5) / 2, (1 - 5**0.5) / 2
def fib_exacto(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
def fib_binet(n):
return round(phi**n / 5**0.5) # el modo de psi ya no hace falta
print("F_30 =", fib_exacto(30), "y con Binet", fib_binet(30))
primer_fallo = next(n for n in range(200) if fib_binet(n) != fib_exacto(n))
print("Binet en coma flotante falla por primera vez en n =", primer_fallo)
print(" exacto:", fib_exacto(primer_fallo), " Binet:", fib_binet(primer_fallo))
F = np.array([[1, 1], [1, 0]], dtype=object)
print("F_100 con la matriz entera:", potencia_cuadrados(F, 100)[0, 1])
F71≈3.1⋅1014 is still exactly representable in double precision (all integers up to 253≈9⋅1015 are); φ71 fails because its relative error, multiplied by 3⋅1014, already exceeds 1/2. The third cell measures the danger of diagonalizing nearly defective matrices: Aε=[0.9ε10.9], with A20 by squaring as reference.
[ ]Diagonalizing a nearly defective matrixBrowser
print(f"{'eps':>8} {'cond(V)':>10} {'error de V L^20 V^-1':>22}")
for eps in [1e-2, 1e-4, 1e-6, 1e-8, 1e-10, 1e-12, 1e-14]:
A = np.array([[0.9, 1.0], [eps, 0.9]])
lam, V, Vinv = diagonalizar(A)
ref = potencia_cuadrados(A, 20)
err = np.linalg.norm(potencia_diag(A, 20) - ref) / np.linalg.norm(ref)
print(f"{eps:8.0e} {np.linalg.cond(V):10.1e} {err:22.1e}")
Conditioning of V rises as 1/ε and error from 10−16 to about 10−10: six digits lost although the matrix looks ordinary.
The exponential three ways
Truncated Taylor series uses the definition; diagonalization uses formula VeΛV−1. Compare both with scipy.linalg.expm on Moler and Van Loan’s classic example A0=[−49−642431], with eigenvalues −1 and −17, multiplied by t.
[ ]Direct Taylor versus diagonalizationBrowser
from scipy.linalg import expm
def expm_taylor(A, N=200):
"""Suma directa de la serie con N términos."""
S = np.eye(len(A))
T = np.eye(len(A))
for k in range(1, N):
T = T @ A / k
S = S + T
return S
def expm_diag(A):
lam, V = np.linalg.eig(A)
return ((V * np.exp(lam)) @ np.linalg.inv(V)).real
A0 = np.array([[-49.0, 24.0], [-64.0, 31.0]])
print(f"{'t':>3} {'Taylor':>10} {'diagonal':>10} (error relativo frente a expm)")
for t in [1, 2, 3, 5]:
ref = expm(t * A0)
e1 = np.linalg.norm(expm_taylor(t * A0) - ref) / np.linalg.norm(ref)
e2 = np.linalg.norm(expm_diag(t * A0) - ref) / np.linalg.norm(ref)
print(f"{t:3d} {e1:10.1e} {e2:10.1e}")
Ae = np.array([[-1.0, 1.0], [1e-14, -1.0]]) # casi defectiva
ref = expm(Ae)
print("casi defectiva, error de la diagonal:", np.linalg.norm(expm_diag(Ae) - ref) / np.linalg.norm(ref))
Direct Taylor becomes a disaster from t=2. Each term is theoretically exact, but intermediates of ∑k(tA0)k/k! become enormous (with t=3, eigenvalue −51 produces terms of size 5151/51!≈1021) and cancel to yield order 10−1, so rounding in large terms destroys all digits. This is catastrophic cancellation. Diagonalization succeeds here because eigenvectors are reasonably separated but loses many digits for the nearly defective matrix.
The standard solution is scaling and squaring: by property 2, eA=(eA/2s)2s. Choose s so ∥A/2s∥≤1/2; the series then has no large terms, converges quickly and avoids cancellation, then square s times. You will implement it in the code exercise. Libraries replace the Taylor polynomial with a rational Padé approximant and choose s and degree using rigorous error bounds.
Finally, the continuous-flow interactive’s damped oscillator in its initial state: eigenvalues λ=−0.1±i, i.e. x′′=(λ1+λ2)x′−λ1λ2x=−0.2x′−1.01x, with step Δt=0.5:
[ ]Exact discretization versus EulerBrowser
import matplotlib.pyplot as plt
sigma, omega, dt, pasos = -0.1, 1.0, 0.5, 60 # autovalores sigma ± i·omega
A = np.array([[0.0, 1.0], [-(sigma**2 + omega**2), 2 * sigma]]) # x'' = 2σx' − |λ|²x
Ad = expm(dt * A) # exacta
Ae = np.eye(2) + dt * A # Euler explícito
x0 = np.array([2.6, 0.0])
X_ex, X_eu = [x0], [x0]
for _ in range(pasos):
X_ex.append(Ad @ X_ex[-1])
X_eu.append(Ae @ X_eu[-1])
X_ex, X_eu = np.array(X_ex), np.array(X_eu)
t = dt * np.arange(pasos + 1)
verdad = np.array([expm(tk * A) @ x0 for tk in t])
print("error máximo de la discretización exacta:", np.abs(X_ex - verdad).max())
print("|autovalores| exacta:", np.abs(np.linalg.eigvals(Ad)), " Euler:", np.abs(np.linalg.eigvals(Ae)))
h = dt / 10 # curva continua: e^{hA} repetida, exacta en cada muestra
E, curva = expm(h * A), [x0]
for _ in range(10 * pasos):
curva.append(E @ curva[-1])
tt, curva = h * np.arange(10 * pasos + 1), np.array(curva)
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.plot(tt, curva[:, 0], color="0.35", lw=1.5, label="solución exacta")
ax.plot(t, X_ex[:, 0], "o", ms=4, label="discretización exacta")
ax.plot(t, X_eu[:, 0], "o-", ms=3, lw=0.8, label="Euler explícito")
ax.set_ylim(-8, 8)
ax.set_xlabel("t")
ax.set_ylabel("posición $x_1$")
ax.legend(loc="upper left")
plt.show()
Exact discretization matches the solution up to rounding; Euler has eigenvalue magnitude 1.074 and amplitude grows by just over 7% per step even as the real system loses energy.
The professional version
SciPy implements all matrix functions in this lesson; know what each does internally:
Function
Calculates
How (and why it does not diagonalize)
scipy.linalg.expm(A)
eA
scaling and squaring with variable-degree Padé approximants (Al-Mohy and Higham, 2009)
scipy.sparse.linalg.expm_multiply(A, v)
etAv without forming etA
matrix-vector products with truncated Taylor and scaling; ideal for large sparse A
scipy.linalg.sqrtm(A), logm(A)
principal square root and logarithm
Schur decomposition, stable even when A is nearly defective
scipy.linalg.funm(A, f)
f(A) for any scalar f
Schur and Parlett recurrence; loses accuracy with very close eigenvalues
np.linalg.matrix_power(A, k)
Ak
exponentiation by squaring, like potencia_cuadrados
torch.linalg.matrix_exp(A)
batched eA on GPU, differentiable
scaling and squaring; suitable inside a network
[ ]Matrix functions with SciPyBrowser
from scipy.linalg import sqrtm, logm, funm
from scipy.sparse.linalg import expm_multiply
A = np.array([[1.0, 0.4], [0.2, 0.8]])
R = sqrtm(A)
print("sqrt(A) =\n", R, "\n¿R @ R == A?", np.allclose(R @ R, A))
print("¿expm(logm(A)) == A?", np.allclose(expm(logm(A)), A))
print("¿funm(A, cos) == Re e^{iA}?", np.allclose(funm(A, np.cos), expm(1j * A).real))
# e^{A+B} frente a e^A e^B con matrices que no conmutan
N1 = np.array([[0.0, 1.0], [0.0, 0.0]])
N2 = N1.T
print("e^(A+B) =\n", expm(N1 + N2))
print("e^A e^B =\n", expm(N1) @ expm(N2))
# e^{tJ} v en 5 instantes entre 0 y pi, sin formar e^{tJ}
J = np.array([[0.0, -1.0], [1.0, 0.0]])
print(expm_multiply(J, np.array([1.0, 0.0]), start=0, stop=np.pi, num=5, endpoint=True).round(6))
The correspondence is direct: expm is your scaling and squaring with a better polynomial; sqrtm, logm and funm are Vf(Λ)V−1 with ill-conditioned V replaced by unitary Q and a triangular matrix. In PyTorch, SSM discretization is torch.linalg.matrix_exp(dt * A) or, if A is diagonal (usual), torch.exp(dt * a) elementwise:
import torchdef discretizar_zoh(a, B, dt): """SSM diagonal: a (n,) autovalores continuos, B (n, d). Devuelve A_bar (n,) y B_bar (n, d).""" a_bar = torch.exp(dt * a) # e^{dt A} con A = diag(a) b_bar = ((a_bar - 1) / a)[:, None] * B # A^{-1}(e^{dt A} - I) B, fila a fila return a_bar, b_bar
Common mistakes
Exercises
ProofDiagonalizable exactly when there is an eigenvector basis
Prove: A∈Cn×n is diagonalizable if and only if there is a basis of Cn consisting of eigenvectors of A.
0
Write V=[v1⋯vn] and Λ=diag(λ1,…,λn).
Step 1 of 4. (⇒) Suppose A=VΛV−1. Which equality should be read column by column?
Prove: If ρ(A)<1, then Ak→0. First for diagonalizable A, then for all A using Jordan form.
0
Use the Euclidean-induced matrix norm, which is submultiplicative: ∥MN∥2≤∥M∥2∥N∥2.
Step 1 of 4. With A=VΛV−1, how do you write Ak?
NumericFibonacci by diagonalization
Using Binet's formula Fk=(φk−ψk)/5 and F0=0, F1=1, calculate F30.
NumericA power without matrix multiplication
Given A=[10.20.40.8]=Vdiag(1.2,0.6)V−1 and V=[21−11], calculate entry (2,1) of A10.
NumericExponential of a rotation generator
For A=[01−10] and t=π/2, calculate entry (2,1) of etA.
NumericDeterminant of an exponential
Calculate det(eA) for A=[132−4] without calculating eA.
NumericEuler's maximum step
The interactive oscillator has eigenvalues λ=−0.1±i. What is the largest Δt for which explicit Euler, xk+1=(I+ΔtA)xk, is stable?
QuizExponential of a sum
Which condition guarantees eA+B=eAeB?
QuizWhat survives in a saddle
xk+1=Axk has eigenvalues 0.5 (eigenvector v1) and −1.2 (eigenvector v2). For which x0 does xk→0?
QuizWhat the spectral radius guarantees
A real matrix A has ρ(A)=0.5. What can you guarantee?
QuizSquare roots of the identity
How many real 2×2 matrices X satisfy X2=I?
QuizTwo continuous systems, the same samples
With step size Δt=1, which continuous eigenvalue gives the same discrete eigenvalue eΔtλ as λ=−0.1+0.5i?
CodeThe exponential by scaling and squaring
Implement expm_scaling_squaring(A, m=16) without using scipy.linalg.expm: choose the smallest integer s≥0 with ∥A∥1/2s≤1/2, sum the degree-m Taylor polynomial of B=A/2s, and square the result s times. The tests compare with scipy.linalg.expm on large-norm matrices, including the Moler and Van Loan example with t=3, where the direct series gives a relative error of order 106, and a nearly defective matrix.
import numpy as np
def expm_scaling_squaring(A, m=16):
"""Devuelve e^A por escalado y cuadrado con Taylor de grado m."""
A = np.asarray(A, dtype=float)
# 1. s: el menor entero >= 0 con norma1(A) / 2**s <= 1/2
# 2. X = I + B + B^2/2! + ... + B^m/m!, con B = A / 2**s
# 3. X = X @ X, s veces
...
Shift+Enter to run
Summary
Diagonalization chooses the eigenvector basis: A=VΛV−1 exists if and only if there are n independent eigenvectors, and in that basis A acts coordinate by coordinate.
Powers and functions pass to the eigenvalues: Ak=VΛkV−1, f(A)=Vf(Λ)V−1. A linear system is a sum of modes ciλikvi (or cieλitvi), and the dominant one wins in the long run.
Stability: in discrete time, ρ(A)<1; in continuous time, Reλ<0. The exponential eΔtA maps one boundary to the other and gives the exact discretization used by SSMs; Euler does not preserve it.
The spectral radius does not tell the whole story: with nearly parallel eigenvectors (large κ(V)), a stable matrix amplifies enormously before decaying.
Jordan form explains the kλk−1 and teλt factors of defective matrices, but is discontinuous: on a computer we use Schur and scaling and squaring, never an ill-conditioned V.
Key idea
In the eigenvector basis, a matrix is a list of numbers: its powers, exponential, and stability can be read from its eigenvalues. What that reading misses is the angle between eigenvectors, where transient growth and numerical instability arise.