Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

9 (advanced, prerequisite). Matrix Calculus for Lagrange’s Equations

ISAE-SUPAERO

This short chapter is a prerequisite for Chapter 10 (Lagrange’s Equations & Fundamental Principles): it works out, once and for all, the vector/matrix calculus identities that let Lagrange’s equations be written directly in the matrix form Mq¨+Cq˙+Kq=FM\ddot q+C\dot q+Kq=F used throughout the rest of these notes (Chapter 5’s eigsort, Chapter 7’s Gershgorin bounds, Chapter 10’s own 2-DOF and double-pendulum examples). It is built from three source materials the reader supplied: two short derivations of the underlying matrix calculus, and a sympy notebook demonstrating a Hessian-based shortcut for recovering a matrix from a quadratic form — which this chapter generalizes into a small, reusable tool for extracting MM, CC, KK directly from a system’s energy expressions, instead of the manual coefficient-matching used in Chapter 10.

import numpy as np
import sympy as sp
from scipy.linalg import eigh

sp.init_printing()
np.set_printoptions(precision=4, suppress=True)

9.1 Why this is worth a chapter of its own

Every energy-method vibration derivation in this book eventually produces two scalar expressions,

2T=q˙TMq˙,2V=qTKq−2qTF2T = \dot q^\mathsf{T} M \dot q, \qquad 2V = q^\mathsf{T} K q - 2q^\mathsf{T}F

(plus, with damping, 2D=q˙TCq˙2D=\dot q^\mathsf{T}C\dot q), and the practical question is always the same: given TT, VV (and DD) written out as scalar sympy expressions, how do I get the matrices M,C,KM,C,K back out? Chapter 10 answers this by hand — differentiate the Euler-Lagrange residual with respect to each q¨i,qi\ddot q_i,q_i and read off the coefficients. That works, but it doesn’t scale, and it obscures a much more direct route: the matrices are just Hessians of the energy expressions. This chapter derives why, and then builds the corresponding sympy helper.

9.2 Theory: the derivative of a quadratic form

9.2.1 A general bilinear identity

For independent vectors y∈Rny\in\mathbb R^n, x∈Rmx\in\mathbb R^m and a constant matrix A∈Rn×mA\in\mathbb R^{n\times m}, the scalar yTAx=∑i,jyiAijxjy^\mathsf{T}Ax=\sum_{i,j}y_iA_{ij}x_j has

∂(yTAx)∂y=Ax\frac{\partial (y^\mathsf{T}Ax)}{\partial y} = Ax

— differentiating a sum that is linear in yy with respect to yy just strips away the yy and leaves the coefficient it multiplied, exactly as ∂(ay)/∂y=a\partial(ay)/\partial y=a does in the scalar case. Componentwise: ∂(yTAx)/∂yk=∑jAkjxj=(Ax)k\partial(y^\mathsf{T}Ax)/\partial y_k=\sum_j A_{kj}x_j=(Ax)_k.

9.2.2 Quadratic forms: setting y=xy=x

Now let y=xy=x (a single vector) and AA be square. The scalar xTAxx^\mathsf{T}Ax is a quadratic form. It is no longer simply linear in xx on both sides, so the identity above cannot be applied naively — but it can be applied twice, once for each occurrence of xx, treating the other occurrence as if it were momentarily a constant vector (the “red/blue” bookkeeping trick: colour one copy of xx red, the other blue, differentiate each in turn using §9.2.1, then add the two contributions back together):

∂(xTAx)∂x=Ax⏟from the blue (right) copy, via yTAx+ATx⏟from the red (left) copy, via xTATy=(A+AT)x\frac{\partial(x^\mathsf{T}Ax)}{\partial x} = \underbrace{Ax}_{\text{from the blue (right) copy, via }y^\mathsf{T}Ax} + \underbrace{A^\mathsf{T}x}_{\text{from the red (left) copy, via }x^\mathsf{T}A^\mathsf{T}y} = (A+A^\mathsf{T})x

For the symmetric matrices that arise from physical energies (M=MTM=M^\mathsf{T}, K=KTK=K^\mathsf{T}, C=CTC=C^\mathsf{T} — inertia, stiffness and damping are always symmetric for a system derived from a single scalar energy function), AT=AA^\mathsf{T}=A and this collapses to the identity used throughout this book:

 ∂(xTMx)∂x=2Mx (M=MT)\boxed{\ \frac{\partial(x^\mathsf{T}Mx)}{\partial x}=2Mx\ } \qquad (M=M^\mathsf{T})

Let’s verify this symbolically for a small generic (non-symmetric, to see the general case) matrix, then again enforcing symmetry:

n = 3
x_syms = sp.symbols(f"x1:{n+1}")
x_vec = sp.Matrix(x_syms)
A_generic = sp.Matrix(n, n, lambda i, j: sp.Symbol(f"a{i}{j}"))

quad = (x_vec.T * A_generic * x_vec)[0]
grad = sp.Matrix([sp.diff(quad, xi) for xi in x_syms])
expected = (A_generic + A_generic.T) * x_vec
print("gradient - (A+A^T)x  (should be the zero vector):")
sp.simplify(grad - expected)
gradient - (A+A^T)x  (should be the zero vector):
Loading...

9.3 From the gradient to the Hessian: recovering MM automatically

This is exactly the trick used in the uploaded quadraticform.ipynb: differentiating the gradient 2Mx2Mx once more with respect to xx gives the (constant) Hessian matrix 2M2M — so MM can be read off a quadratic-form expression purely mechanically, with no coefficient-matching by hand:

Hessianx(xTMx)=2M(M=MT)\text{Hessian}_x\big(x^\mathsf{T}Mx\big) = 2M \qquad (M=M^\mathsf{T})

Reproducing that notebook’s own check here, with its exact numbers:

x1, x2, x3, x4 = sp.symbols("x1 x2 x3 x4")
A = sp.Matrix([
    [3, 2, 0, 5],
    [2, -1, 4, -3],
    [0, 4, -2, -4],
    [5, -3, -4, 7],
])
xv = sp.Matrix([x1, x2, x3, x4])
quad_expr = sp.expand((xv.T * A * xv)[0])
print("x^T A x =", quad_expr)

H = sp.hessian(quad_expr, [x1, x2, x3, x4])
A_recovered = H / 2
print("Recovered A =\n", A_recovered)
print("Matches original A:", A_recovered == A)
x^T A x = 3*x1**2 + 4*x1*x2 + 10*x1*x4 - x2**2 + 8*x2*x3 - 6*x2*x4 - 2*x3**2 - 8*x3*x4 + 7*x4**2
Recovered A =
 Matrix([[3, 2, 0, 5], [2, -1, 4, -3], [0, 4, -2, -4], [5, -3, -4, 7]])
Matches original A: True

9.4 The matrix form of Lagrange’s equations

Now apply the same idea to the physical energies rather than an abstract quadratic form. For a linear(ized) multi-DOF system,

2T=q˙TMq˙,2D=q˙TCq˙,2V=qTKq−2qTF2T=\dot q^\mathsf{T}M\dot q,\qquad 2D=\dot q^\mathsf{T}C\dot q, \qquad 2V=q^\mathsf{T}Kq-2q^\mathsf{T}F

with M,C,KM,C,K symmetric and FF the vector of external generalized forces. Substituting into the Euler-Lagrange equation with a Rayleigh dissipation function,

ddt(∂T∂q˙)−∂T∂q+∂D∂q˙+∂V∂q=0,\frac{d}{dt}\Big(\frac{\partial T}{\partial\dot q}\Big) - \frac{\partial T}{\partial q} + \frac{\partial D}{\partial\dot q} + \frac{\partial V}{\partial q} = 0,

and using §9.2.2’s identity term by term — ∂T/∂q˙=Mq˙\partial T/\partial\dot q=M\dot q (so d/dt(⋅)=Mq¨d/dt(\cdot)=M\ddot q for constant MM), ∂T/∂q=0\partial T/\partial q=0 (no explicit qq-dependence once MM is constant), ∂D/∂q˙=Cq˙\partial D/\partial\dot q=C\dot q, ∂V/∂q=Kq−F\partial V/\partial q=Kq-F — gives exactly the matrix equation used everywhere in this book:

 Mq¨+Cq˙+Kq=F \boxed{\ M\ddot q + C\dot q + Kq = F\ }

The table below (from the reference material) makes the term-by-term correspondence explicit — each physical ingredient contributes to exactly one matrix:

Energy termContributes toVia
2T=q˙TMq˙2T=\dot q^\mathsf{T}M\dot qMass/inertia matrix MMddt∂T∂q˙=Mq¨\dfrac{d}{dt}\dfrac{\partial T}{\partial\dot q}=M\ddot q
2D=q˙TCq˙2D=\dot q^\mathsf{T}C\dot qDamping matrix CC∂D∂q˙=Cq˙\dfrac{\partial D}{\partial\dot q}=C\dot q
2V=qTKq2V=q^\mathsf{T}KqStiffness matrix KK∂V∂q=Kq\dfrac{\partial V}{\partial q}=Kq
−2qTF-2q^\mathsf{T}F (part of 2V2V)Force vector FF−∂∂q(−qTF)=F-\dfrac{\partial}{\partial q}(-q^\mathsf{T}F)=F

This is precisely why Chapter 10 could read MM and KK straight off the 2-DOF spring system’s T,VT,V: it was implicitly using this identity, just applying it by hand one coefficient at a time instead of via a Hessian.

9.5 Hands-on: automating M,C,KM,C,K extraction with sympy

Here is the reusable tool this chapter set out to build — a direct generalization of quadraticform.ipynb’s Hessian trick to full Lagrangian mechanics:

def matrices_from_energies(T, V, q, qd, D=None):
    """Extract the (constant) mass, damping and stiffness matrices from scalar energy
    expressions T(qd), V(q) and, optionally, a Rayleigh dissipation function D(qd).

    Valid whenever T is an exact quadratic form in `qd` with q-independent coefficients (the
    standard linear-vibration assumption used throughout this book); for a configuration-
    dependent mass matrix M(q) (as in several of the ``lagrange_examples/`` notebooks), evaluate
    T's Hessian at the configuration of interest instead (e.g. the equilibrium) before calling.

    Parameters
    ----------
    T, V, D : sympy expressions
        Kinetic energy, potential energy, and (optional) Rayleigh dissipation function.
    q, qd : sequences of sympy symbols/functions
        Generalized coordinates and their (time) derivatives, in matching order.

    Returns
    -------
    M, C, K : sympy Matrix
        Mass, damping and stiffness matrices, with 2T=qd^T M qd, 2D=qd^T C qd, 2V=q^T K q
        (up to any q-independent forcing terms already removed from V).
    """
    M = sp.hessian(T, qd)
    K = sp.hessian(V, q)
    C = sp.hessian(D, qd) if D is not None else sp.zeros(len(q))
    return sp.simplify(M), sp.simplify(C), sp.simplify(K)

Validation 1 — Chapter 10’s 2-DOF mass-spring system

Re-deriving Chapter 10 §10.2’s example (m1,m2m_1,m_2 connected to a wall and to each other by k1,k2,k3k_1,k_2,k_3) with matrices_from_energies instead of manual coefficient-matching:

t = sp.symbols("t")
m1, m2, k1, k2, k3 = sp.symbols("m1 m2 k1 k2 k3", positive=True)
x1t = sp.Function("x1")(t)
x2t = sp.Function("x2")(t)
x1d, x2d = sp.diff(x1t, t), sp.diff(x2t, t)

T_spring = sp.Rational(1, 2) * m1 * x1d**2 + sp.Rational(1, 2) * m2 * x2d**2
V_spring = (sp.Rational(1, 2) * k1 * x1t**2 + sp.Rational(1, 2) * k2 * (x2t - x1t) ** 2
            + sp.Rational(1, 2) * k3 * x2t**2)

M_auto, C_auto, K_auto = matrices_from_energies(T_spring, V_spring, [x1t, x2t], [x1d, x2d])
print("M (Hessian-extracted) =\n", M_auto)
print("K (Hessian-extracted) =\n", K_auto)
M (Hessian-extracted) =
 Matrix([[m1, 0], [0, m2]])
K (Hessian-extracted) =
 Matrix([[k1 + k2, -k2], [-k2, k2 + k3]])

This is exactly M=diag(m1,m2)M=\mathrm{diag}(m_1,m_2) and K=[k1+k2−k2−k2k2+k3]K=\begin{bmatrix}k_1+k_2&-k_2\\-k_2&k_2+k_3\end{bmatrix} — matching Chapter 10’s manually coefficient-matched result, with no manual algebra at all.

Validation 2 — the linearized double pendulum

Chapter 10 §10.3 linearizes the double pendulum via a formal ε\varepsilon-expansion of the equations of motion. An equivalent (and often more direct) route is to expand the Lagrangian itself to quadratic order in the small quantities and only then apply matrices_from_energies — the two routes must agree, since Lagrange’s equations commute with truncating a power series at a fixed order.

m, l, g, eps = sp.symbols("m l g epsilon", positive=True)
th1 = sp.Function("theta1")(t)
th2 = sp.Function("theta2")(t)
th1e, th2e = eps * th1, eps * th2

x1p = l * sp.sin(th1e)
y1p = -l * sp.cos(th1e)
x2p = x1p + l * sp.sin(th2e)
y2p = y1p - l * sp.cos(th2e)

T_full = (sp.Rational(1, 2) * m * (sp.diff(x1p, t) ** 2 + sp.diff(y1p, t) ** 2)
          + sp.Rational(1, 2) * m * (sp.diff(x2p, t) ** 2 + sp.diff(y2p, t) ** 2))
V_full = m * g * y1p + m * g * y2p
L_full = sp.expand(T_full - V_full)

L_series = sp.series(L_full, eps, 0, 3).removeO()
L2 = sp.expand(L_series.coeff(eps, 2))  # quadratic-order Lagrangian

th1d, th2d = sp.diff(th1, t), sp.diff(th2, t)
V2 = -L2.subs({th1d: 0, th2d: 0})   # at zero velocity, L2 = T2 - V2 = -V2
T2 = sp.expand(L2 + V2)             # so T2 = L2 + V2

M_pend2, C_pend2, K_pend2 = matrices_from_energies(T2, V2, [th1, th2], [th1d, th2d])
print("M (from quadratic Lagrangian, Hessian) =\n", M_pend2)
print("K (from quadratic Lagrangian, Hessian) =\n", K_pend2)
M (from quadratic Lagrangian, Hessian) =
 Matrix([[2*l**2*m, l**2*m], [l**2*m, l**2*m]])
K (from quadratic Lagrangian, Hessian) =
 Matrix([[2*g*l*m, 0], [0, g*l*m]])
subs_num = {m: 1.0, l: 1.0, g: 9.81}
M_num2 = np.array(M_pend2.subs(subs_num)).astype(float)
K_num2 = np.array(K_pend2.subs(subs_num)).astype(float)
lam2, _ = eigh(K_num2, M_num2)
wn2 = np.sqrt(lam2)
wn_exact = np.sqrt(np.array([2 - np.sqrt(2), 2 + np.sqrt(2)]) * 9.81 / 1.0)
print("Natural frequencies from Hessian-extracted M,K:", np.sort(wn2))
print("Exact closed form sqrt((2-/+sqrt2)*g/l):        ", np.sort(wn_exact))
Natural frequencies from Hessian-extracted M,K: [2.3972 5.7874]
Exact closed form sqrt((2-/+sqrt2)*g/l):         [2.3972 5.7874]

The Hessian-extracted matrices reproduce Chapter 10’s natural frequencies exactly (both routes — expanding the equations, or expanding the Lagrangian first — must agree, and they do). This is the payoff of this prerequisite chapter: once TT and VV are written down, sympy’s hessian() gets you straight to MM and KK, for a 2-DOF system or a 20-DOF one, without ever hand-differentiating an Euler-Lagrange residual.

9.6 List of example notebooks

Matthew Kelly’s Lagrange_Mechanics_Derivations is a MATLAB repository of worked Lagrangian-mechanics derivations (Symbolic Math Toolbox + Newton-Euler cross-checks, one folder per system). As requested, every system in that repository has been independently re-derived in Python/sympy — not machine-translated line-by-line from the MATLAB source, but rebuilt from the same physical setup using the tools built in this chapter and Chapter 10 — and lives in advanced/lagrange_examples/:

#NotebookSystem (original MATLAB folder)
1Simple harmonic oscillatorsimpleHarmonicOscillator/
2Single pendulumsinglePendulum/
3Double pendulum (nonlinear simulation)doublePendulum/
4Double pendulum, actuated at the shoulderdoublePendulumForced/
5N-link pendulum (generalized)nLinkPendulum/
6Point mass in polar coordinates / pumped pendulumpolarPointMass/
7Rolling disk with a pendulumrollingCartPole/
8Cart-pole with a springspringCartPole/
9Thrust-controlled point-mass “rocket”simpleRocket/ (translated as a point-mass simplification — see the notebook’s note)

Every notebook in the table follows the same pattern taught in this chapter: write TT and VV (and QQ, for actuated systems) as sympy expressions, derive the Euler-Lagrange equations with a small reusable lagrange_equations() helper, solve the resulting linear-in-q¨\ddot q system for the accelerations, and either extract M,KM,K (linear systems) or integrate the exact nonlinear equations numerically with scipy.integrate.solve_ivp (nonlinear systems) — no hand-written free-body diagrams anywhere.

9.6.2 Further practice: resonance (Python, Univ. of California Davis)

moorepants.github.io/resonance is an existing, already-Python collection of interactive mechanical-vibration teaching notebooks (Jason Moore’s ENG 122 course materials), listed here for further practice rather than translated (it is already Python-based):

Course offeringSelected notebooks
ENG 122, Winter 2020 (12 notebooks)Book oscillating on a cylindrical cup · Bicycle wheel inertia · Curve fitting · Clock pendulum with air-drag / with friction damping · Compound pendulums & center of percussion · 1-DOF trifilar pendulum · 2-DOF “bouncy” pendulum · Ball-channel pendulum & its modes · Sinusoidal forcing · Vibrating building under forcing
ENG 122, Fall 2017 (14 notebooks)Introduction to Jupyter · Book-on-cup & bicycle-wheel labs · Clock pendulum (air drag / joint friction) · Sinusoidal forcing · Vertical vibration of a quarter car · Drone swinging from a trifilar pendulum · Washing-machine model · Ball-channel pendulum & its modes · Modes of a vibrating building · Vibrating building under forcing · Bicycle dynamics

Open the site directly for the notebooks themselves and their downloadable data packages — a good next step after this chapter’s gallery for more experimentally-flavoured (parameter identification from real measurements) vibration modeling.