22  Quadratic Forms and Optimization Geometry

22.1 Opening question

A symmetric matrix does not only transform vectors. It also defines a geometric landscape.

Given a symmetric matrix \(A\), the expression

\[ x^TAx \]

assigns a number to each vector \(x\).

For example, in two variables,

\[ x= \begin{bmatrix} x_1\\ x_2 \end{bmatrix}, \qquad A= \begin{bmatrix} a&b\\ b&c \end{bmatrix}, \]

we get

\[ x^TAx=ax_1^2+2bx_1x_2+cx_2^2. \]

This is a quadratic form.

Quadratic forms describe ellipses, hyperbolas, paraboloids, energy landscapes, curvature, optimization problems, covariance geometry, and least-squares objectives.

The central question of this chapter is:

How does a symmetric matrix shape a quadratic landscape?

The answer comes from eigenvalues and eigenvectors.

22.2 Learning goals

After studying this chapter, you should be able to:

  1. Define a quadratic form.
  2. Write a quadratic form as \(x^TAx\) using a symmetric matrix.
  3. Classify quadratic forms using eigenvalues.
  4. Understand positive definite, positive semidefinite, negative definite, and indefinite matrices.
  5. Use orthogonal diagonalization to remove cross terms.
  6. Interpret level curves and level surfaces geometrically.
  7. Connect quadratic forms to optimization.
  8. Understand the Hessian matrix and curvature.
  9. Analyze least-squares objectives as quadratic functions.
  10. Use Python to visualize quadratic forms and optimization geometry.

22.3 20.1 Quadratic forms

A quadratic form on \(\mathbb{R}^n\) is a function

\[ q(x)=x^TAx, \]

where \(A\) is an \(n\times n\) matrix.

Usually, we take \(A\) to be symmetric.

Why?

Because only the symmetric part of \(A\) affects \(x^TAx\).

Every square matrix \(A\) can be split as

\[ A=\frac{A+A^T}{2}+\frac{A-A^T}{2}. \]

The first part is symmetric, and the second part is skew-symmetric.

For every vector \(x\),

\[ x^T\left(\frac{A-A^T}{2}\right)x=0. \]

So

\[ x^TAx=x^T\left(\frac{A+A^T}{2}\right)x. \]

Thus every quadratic form can be represented by a symmetric matrix.

NoteDefinition: quadratic form

A quadratic form is a function

\[ q(x)=x^TAx, \]

where \(A\) is a symmetric matrix.

22.4 20.2 First examples

22.4.1 Example 1: circular quadratic form

Let

\[ A= \begin{bmatrix} 1&0\\ 0&1 \end{bmatrix} =I. \]

Then

\[ q(x)=x^TIx=x_1^2+x_2^2. \]

The level set

\[ x_1^2+x_2^2=1 \]

is a circle.

22.4.2 Example 2: elliptical quadratic form

Let

\[ A= \begin{bmatrix} 4&0\\ 0&1 \end{bmatrix}. \]

Then

\[ q(x)=4x_1^2+x_2^2. \]

The level set

\[ 4x_1^2+x_2^2=1 \]

is an ellipse.

22.4.3 Example 3: indefinite quadratic form

Let

\[ A= \begin{bmatrix} 1&0\\ 0&-1 \end{bmatrix}. \]

Then

\[ q(x)=x_1^2-x_2^2. \]

This can be positive, negative, or zero depending on \(x\).

The level sets are hyperbolas.

22.5 20.3 Python plot: level curves of quadratic forms

import numpy as np
import matplotlib.pyplot as plt

def plot_quadratic_contours(A, title, xlim=(-2, 2), ylim=(-2, 2)):
    x = np.linspace(xlim[0], xlim[1], 300)
    y = np.linspace(ylim[0], ylim[1], 300)
    X, Y = np.meshgrid(x, y)

    Z = (
        A[0, 0] * X**2
        + (A[0, 1] + A[1, 0]) * X * Y
        + A[1, 1] * Y**2
    )

    plt.figure(figsize=(6, 6))
    cs = plt.contour(X, Y, Z, levels=15)
    plt.clabel(cs, inline=True, fontsize=8)
    plt.axhline(0, linewidth=0.8)
    plt.axvline(0, linewidth=0.8)
    plt.grid(True)
    plt.axis("equal")
    plt.title(title)
    plt.show()

A_circle = np.array([[1, 0],
                     [0, 1]], dtype=float)

A_ellipse = np.array([[4, 0],
                      [0, 1]], dtype=float)

A_saddle = np.array([[1, 0],
                     [0, -1]], dtype=float)

plot_quadratic_contours(A_circle, "$x_1^2+x_2^2$")
plot_quadratic_contours(A_ellipse, "$4x_1^2+x_2^2$")
plot_quadratic_contours(A_saddle, "$x_1^2-x_2^2$")

22.6 20.4 Cross terms

A quadratic form may include cross terms.

For example,

\[ q(x_1,x_2)=2x_1^2+4x_1x_2+2x_2^2. \]

This can be written as

\[ q(x)=x^TAx \]

with

\[ A= \begin{bmatrix} 2&2\\ 2&2 \end{bmatrix}. \]

Indeed,

\[ x^TAx = \begin{bmatrix} x_1&x_2 \end{bmatrix} \begin{bmatrix} 2&2\\ 2&2 \end{bmatrix} \begin{bmatrix} x_1\\ x_2 \end{bmatrix}. \]

Multiplying gives

\[ 2x_1^2+4x_1x_2+2x_2^2. \]

The off-diagonal entries split the cross term.

For a symmetric \(2\times 2\) matrix

\[ A= \begin{bmatrix} a&b\\ b&c \end{bmatrix}, \]

we have

\[ x^TAx=ax_1^2+2bx_1x_2+cx_2^2. \]

22.7 20.5 Writing a quadratic form as a matrix

Suppose

\[ q(x_1,x_2)=5x_1^2-6x_1x_2+2x_2^2. \]

The matrix is

\[ A= \begin{bmatrix} 5&-3\\ -3&2 \end{bmatrix}. \]

Why?

Because the cross term coefficient \(-6\) is split equally:

\[ 2a_{12}=-6, \]

so

\[ a_{12}=a_{21}=-3. \]

Thus

\[ q(x)=x^TAx. \]

TipBuilding a symmetric matrix from a quadratic form

For a term \(cx_ix_j\) with \(i\ne j\), place \(c/2\) in entries \((i,j)\) and \((j,i)\).

22.8 20.6 Orthogonal diagonalization removes cross terms

Let \(A\) be symmetric. By the spectral theorem,

\[ A=QDQ^T, \]

where \(Q\) is orthogonal and \(D\) is diagonal.

Then

\[ x^TAx=x^TQDQ^Tx. \]

Let

\[ y=Q^Tx. \]

Since \(Q\) is orthogonal, this is a rotation or reflection of coordinates.

Then

\[ x^TAx=y^TDy. \]

If

\[ D=\operatorname{diag}(\lambda_1,\ldots,\lambda_n), \]

then

\[ y^TDy=\lambda_1y_1^2+\cdots+\lambda_ny_n^2. \]

The cross terms disappear.

ImportantPrincipal axes form

If \(A=QDQ^T\) and \(y=Q^Tx\), then

\[ x^TAx=\lambda_1y_1^2+\cdots+\lambda_ny_n^2. \]

The eigenvectors give the principal axes of the quadratic form.

The eigenvalues give curvature along those axes.

22.9 20.7 Example: diagonalizing a quadratic form

Let

\[ A= \begin{bmatrix} 2&1\\ 1&2 \end{bmatrix}. \]

The eigenvectors are

\[ q_1=\frac{1}{\sqrt{2}} \begin{bmatrix} 1\\ 1 \end{bmatrix}, \qquad q_2=\frac{1}{\sqrt{2}} \begin{bmatrix} 1\\ -1 \end{bmatrix}. \]

The corresponding eigenvalues are

\[ 3 \quad \text{and} \quad 1. \]

Thus

\[ A=QDQ^T, \]

where

\[ Q= \frac{1}{\sqrt{2}} \begin{bmatrix} 1&1\\ 1&-1 \end{bmatrix}, \qquad D= \begin{bmatrix} 3&0\\ 0&1 \end{bmatrix}. \]

The quadratic form is

\[ x^TAx=2x_1^2+2x_1x_2+2x_2^2. \]

In eigenvector coordinates \(y=Q^Tx\), it becomes

\[ 3y_1^2+y_2^2. \]

The cross term disappears.

22.10 20.8 Python plot: rotated ellipse

A = np.array([[2, 1],
              [1, 2]], dtype=float)

plot_quadratic_contours(A, "$2x_1^2+2x_1x_2+2x_2^2$")

The level curves are ellipses whose axes are not aligned with the standard coordinate axes.

The eigenvectors identify the rotated principal axes.

eigvals, Q = np.linalg.eigh(A)

plt.figure(figsize=(6, 6))
x = np.linspace(-2, 2, 300)
y = np.linspace(-2, 2, 300)
X, Y = np.meshgrid(x, y)
Z = A[0, 0]*X**2 + 2*A[0, 1]*X*Y + A[1, 1]*Y**2

cs = plt.contour(X, Y, Z, levels=10)
plt.clabel(cs, inline=True, fontsize=8)

for j in range(2):
    q = Q[:, j]
    plt.arrow(0, 0, q[0], q[1], head_width=0.06, length_includes_head=True)
    plt.arrow(0, 0, -q[0], -q[1], head_width=0.06, length_includes_head=True)
    plt.text(1.1*q[0], 1.1*q[1], f"$q_{j+1}$")

plt.axhline(0, linewidth=0.8)
plt.axvline(0, linewidth=0.8)
plt.grid(True)
plt.axis("equal")
plt.title("Eigenvectors are principal axes of the quadratic form")
plt.show()

eigvals, Q

(array([1., 3.]),
 array([[-0.70710678,  0.70710678],
        [ 0.70710678,  0.70710678]]))

22.11 20.9 Classification by eigenvalues

The sign of the eigenvalues determines the shape of the quadratic form.

Let \(A\) be symmetric.

22.11.1 Positive definite

\(A\) is positive definite if

\[ x^TAx>0 \]

for every nonzero \(x\).

This happens exactly when all eigenvalues of \(A\) are positive.

22.11.2 Positive semidefinite

\(A\) is positive semidefinite if

\[ x^TAx\ge 0 \]

for every \(x\).

This happens exactly when all eigenvalues are nonnegative.

22.11.3 Negative definite

\(A\) is negative definite if

\[ x^TAx<0 \]

for every nonzero \(x\).

This happens exactly when all eigenvalues are negative.

22.11.4 Negative semidefinite

\(A\) is negative semidefinite if

\[ x^TAx\le 0 \]

for every \(x\).

This happens exactly when all eigenvalues are nonpositive.

22.11.5 Indefinite

\(A\) is indefinite if \(x^TAx\) can be positive for some \(x\) and negative for other \(x\).

This happens exactly when \(A\) has both positive and negative eigenvalues.

ImportantEigenvalue classification of quadratic forms

For a symmetric matrix \(A\):

  • all eigenvalues positive: positive definite,
  • all eigenvalues nonnegative: positive semidefinite,
  • all eigenvalues negative: negative definite,
  • all eigenvalues nonpositive: negative semidefinite,
  • mixed positive and negative eigenvalues: indefinite.

22.12 20.10 Examples of classification

22.12.1 Positive definite

\[ A= \begin{bmatrix} 4&0\\ 0&1 \end{bmatrix} \]

has eigenvalues \(4\) and \(1\).

Both are positive, so \(A\) is positive definite.

The level curves are ellipses.

22.12.2 Positive semidefinite

\[ A= \begin{bmatrix} 1&0\\ 0&0 \end{bmatrix} \]

has eigenvalues \(1\) and \(0\).

It is positive semidefinite, but not positive definite.

The quadratic form is

\[ x_1^2. \]

It is zero for all vectors on the \(x_2\)-axis.

22.12.3 Indefinite

\[ A= \begin{bmatrix} 1&0\\ 0&-1 \end{bmatrix} \]

has eigenvalues \(1\) and \(-1\).

It is indefinite.

The quadratic form is

\[ x_1^2-x_2^2. \]

It can be positive, negative, or zero.

22.13 20.11 Python: classification by eigenvalues

def classify_symmetric(A, tol=1e-10):
    eigvals = np.linalg.eigvalsh(A)

    if np.all(eigvals > tol):
        kind = "positive definite"
    elif np.all(eigvals >= -tol) and np.any(np.abs(eigvals) <= tol):
        kind = "positive semidefinite"
    elif np.all(eigvals < -tol):
        kind = "negative definite"
    elif np.all(eigvals <= tol) and np.any(np.abs(eigvals) <= tol):
        kind = "negative semidefinite"
    elif np.any(eigvals > tol) and np.any(eigvals < -tol):
        kind = "indefinite"
    else:
        kind = "borderline / numerical ambiguity"

    return eigvals, kind

matrices = {
    "positive definite": np.array([[4, 0], [0, 1]], dtype=float),
    "positive semidefinite": np.array([[1, 0], [0, 0]], dtype=float),
    "indefinite": np.array([[1, 0], [0, -1]], dtype=float),
    "rotated positive definite": np.array([[2, 1], [1, 2]], dtype=float)
}

for name, A in matrices.items():
    eigvals, kind = classify_symmetric(A)
    print(name)
    print("eigenvalues:", eigvals)
    print("classification:", kind)
    print()
positive definite
eigenvalues: [1. 4.]
classification: positive definite

positive semidefinite
eigenvalues: [0. 1.]
classification: positive semidefinite

indefinite
eigenvalues: [-1.  1.]
classification: indefinite

rotated positive definite
eigenvalues: [1. 3.]
classification: positive definite

22.14 20.12 Positive definite matrices and ellipses

If \(A\) is positive definite, then

\[ x^TAx=c \]

for \(c>0\) is an ellipse in \(\mathbb{R}^2\) or an ellipsoid in higher dimensions.

Using the spectral theorem,

\[ x^TAx=\lambda_1y_1^2+\lambda_2y_2^2. \]

For \(c=1\),

\[ \lambda_1y_1^2+\lambda_2y_2^2=1. \]

This can be written as

\[ \frac{y_1^2}{1/\lambda_1}+\frac{y_2^2}{1/\lambda_2}=1. \]

So the axis lengths are

\[ \frac{1}{\sqrt{\lambda_1}} \quad \text{and} \quad \frac{1}{\sqrt{\lambda_2}}. \]

Large eigenvalues correspond to short axes and steep curvature.

Small eigenvalues correspond to long axes and shallow curvature.

22.15 20.13 Python plot: eigenvalues and ellipse axes

A = np.array([[5, 2],
              [2, 2]], dtype=float)

eigvals, Q = np.linalg.eigh(A)

plot_quadratic_contours(A, "Positive definite quadratic form")

print("eigenvalues:", eigvals)
print("axis lengths for level x^T A x = 1:", 1 / np.sqrt(eigvals))

eigenvalues: [1. 6.]
axis lengths for level x^T A x = 1: [1.         0.40824829]

The eigenvectors give directions of the ellipse axes.

The eigenvalues determine the inverse squared axis lengths.

22.16 20.14 Sylvester’s criterion for \(2\times 2\) matrices

For a symmetric \(2\times 2\) matrix

\[ A= \begin{bmatrix} a&b\\ b&c \end{bmatrix}, \]

there is a useful test for positive definiteness.

The matrix is positive definite if and only if

\[ a>0 \]

and

\[ \det(A)>0. \]

ImportantPositive definiteness test for \(2\times 2\) matrices

For

\[ A= \begin{bmatrix} a&b\\ b&c \end{bmatrix}, \]

\(A\) is positive definite if and only if

\[ a>0 \quad \text{and} \quad \det(A)>0. \]

This is a special case of Sylvester’s criterion.

For larger symmetric matrices, positive definiteness can be tested using leading principal minors or eigenvalues.

22.17 20.15 Optimization and quadratic functions

A quadratic function has the form

\[ f(x)=\frac12 x^TAx-b^Tx+c, \]

where \(A\) is symmetric.

The gradient is

\[ \nabla f(x)=Ax-b. \]

The Hessian matrix is

\[ \nabla^2 f(x)=A. \]

Thus the symmetric matrix \(A\) controls the curvature of the function.

Critical points satisfy

\[ \nabla f(x)=0. \]

So

\[ Ax=b. \]

If \(A\) is positive definite, then the critical point is the unique global minimum.

ImportantQuadratic minimization

If \(A\) is positive definite, then

\[ f(x)=\frac12x^TAx-b^Tx+c \]

has a unique global minimum at the solution of

\[ Ax=b. \]

22.18 20.16 Completing the square in matrix form

Suppose \(A\) is positive definite.

Let

\[ x_* = A^{-1}b. \]

Then

\[ Ax_*=b. \]

We can rewrite

\[ f(x)=\frac12x^TAx-b^Tx+c \]

as

\[ f(x) = \frac12(x-x_*)^TA(x-x_*)+f(x_*). \]

This shows that the level sets of \(f\) are ellipses centered at \(x_*\).

The matrix \(A\) determines the shape of the ellipses.

The vector \(b\) shifts the center.

22.19 20.17 Python plot: quadratic bowl

A = np.array([[3, 1],
              [1, 2]], dtype=float)

b = np.array([1, 2], dtype=float)

x_star = np.linalg.solve(A, b)

x = np.linspace(-2, 3, 250)
y = np.linspace(-2, 3, 250)
X, Y = np.meshgrid(x, y)

Z = (
    0.5 * (A[0, 0]*X**2 + 2*A[0, 1]*X*Y + A[1, 1]*Y**2)
    - b[0]*X - b[1]*Y
)

plt.figure(figsize=(6, 6))
cs = plt.contour(X, Y, Z, levels=20)
plt.clabel(cs, inline=True, fontsize=8)
plt.scatter([x_star[0]], [x_star[1]], marker="x", s=100)
plt.text(x_star[0] + 0.05, x_star[1] + 0.05, "$x_*$")
plt.axhline(0, linewidth=0.8)
plt.axvline(0, linewidth=0.8)
plt.grid(True)
plt.axis("equal")
plt.title("Contours of a positive definite quadratic function")
plt.show()

x_star

array([0., 1.])

The point \(x_*\) is the unique minimizer.

22.20 20.18 Three-dimensional surface plot

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection="3d")
ax.plot_surface(X, Y, Z, alpha=0.75, linewidth=0)
ax.scatter([x_star[0]], [x_star[1]], [0.5*x_star @ A @ x_star - b @ x_star], s=60)
ax.set_xlabel("$x_1$")
ax.set_ylabel("$x_2$")
ax.set_zlabel("$f(x)$")
ax.set_title("A positive definite quadratic bowl")
plt.show()

A positive definite quadratic function is shaped like a bowl.

A negative definite quadratic function is shaped like an upside-down bowl.

An indefinite quadratic function is shaped like a saddle.

22.21 20.19 Indefinite quadratic functions and saddles

Let

\[ A= \begin{bmatrix} 1&0\\ 0&-1 \end{bmatrix}. \]

Then

\[ f(x)=\frac12x^TAx=\frac12(x_1^2-x_2^2). \]

Along the \(x_1\) direction, the function increases.

Along the \(x_2\) direction, the function decreases.

So the origin is a saddle point, not a minimum or maximum.

A_saddle = np.array([[1, 0],
                     [0, -1]], dtype=float)

x = np.linspace(-2, 2, 250)
y = np.linspace(-2, 2, 250)
X, Y = np.meshgrid(x, y)

Z = 0.5 * (X**2 - Y**2)

plt.figure(figsize=(6, 6))
cs = plt.contour(X, Y, Z, levels=20)
plt.clabel(cs, inline=True, fontsize=8)
plt.axhline(0, linewidth=0.8)
plt.axvline(0, linewidth=0.8)
plt.grid(True)
plt.axis("equal")
plt.title("Indefinite quadratic form: saddle contours")
plt.show()

22.22 20.20 Hessian matrix and local optimization

For a twice differentiable function \(f:\mathbb{R}^n\to\mathbb{R}\), the Hessian matrix is

\[ H(x)= \begin{bmatrix} \frac{\partial^2 f}{\partial x_1^2}&\cdots&\frac{\partial^2 f}{\partial x_1\partial x_n}\\ \vdots&\ddots&\vdots\\ \frac{\partial^2 f}{\partial x_n\partial x_1}&\cdots&\frac{\partial^2 f}{\partial x_n^2} \end{bmatrix}. \]

Near a critical point \(x_*\), a function can be approximated by a quadratic model:

\[ f(x_*+h)\approx f(x_*)+\frac12 h^TH(x_*)h. \]

Thus the eigenvalues of the Hessian determine local shape:

  • all positive eigenvalues: local minimum,
  • all negative eigenvalues: local maximum,
  • mixed signs: saddle point.

This is the second derivative test in multivariable form.

22.23 20.21 Least squares as a quadratic form

The least-squares objective is

\[ f(x)=\frac12\|Ax-b\|^2. \]

Expand:

\[ f(x)=\frac12(Ax-b)^T(Ax-b). \]

This becomes

\[ f(x)=\frac12x^TA^TAx-b^TAx+\frac12b^Tb. \]

The Hessian is

\[ A^TA. \]

Since

\[ x^TA^TAx=\|Ax\|^2\ge 0, \]

the matrix \(A^TA\) is positive semidefinite.

If the columns of \(A\) are independent, then \(A^TA\) is positive definite, and the least-squares objective has a unique minimizer.

The gradient is

\[ \nabla f(x)=A^T(Ax-b). \]

Setting the gradient equal to zero gives the normal equations:

\[ A^TA\hat x=A^Tb. \]

22.24 20.22 Python plot: least-squares objective surface

A = np.array([
    [1, 1],
    [1, 2],
    [1, 3]
], dtype=float)

b = np.array([1, 2, 2], dtype=float)

x_star = np.linalg.lstsq(A, b, rcond=None)[0]

u = np.linspace(-1, 2, 200)
v = np.linspace(-1, 2, 200)
U, V = np.meshgrid(u, v)

Z = np.zeros_like(U)

for i in range(U.shape[0]):
    for j in range(U.shape[1]):
        x_vec = np.array([U[i, j], V[i, j]])
        Z[i, j] = 0.5 * np.linalg.norm(A @ x_vec - b)**2

plt.figure(figsize=(6, 6))
cs = plt.contour(U, V, Z, levels=20)
plt.clabel(cs, inline=True, fontsize=8)
plt.scatter([x_star[0]], [x_star[1]], marker="x", s=100)
plt.text(x_star[0] + 0.05, x_star[1] + 0.05, "$\\hat x$")
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")
plt.grid(True)
plt.axis("equal")
plt.title("Least-squares objective contours")
plt.show()

x_star

array([0.66666667, 0.5       ])

22.25 20.23 Gradient descent on a quadratic

For

\[ f(x)=\frac12x^TAx-b^Tx, \]

where \(A\) is positive definite, gradient descent is

\[ x_{k+1}=x_k-\alpha(Ax_k-b). \]

The error

\[ e_k=x_k-x_* \]

satisfies

\[ e_{k+1}=(I-\alpha A)e_k. \]

Therefore convergence depends on eigenvalues of

\[ I-\alpha A. \]

If \(A\) has eigenvalues \(\lambda_i\), then \(I-\alpha A\) has eigenvalues

\[ 1-\alpha\lambda_i. \]

For convergence, we need

\[ |1-\alpha\lambda_i|<1 \]

for all \(i\).

This gives

\[ 0<\alpha<\frac{2}{\lambda_{\max}}. \]

Eigenvalues determine the allowed step size.

22.26 20.24 Conditioning and elongated contours

If \(A\) is positive definite, its condition number is

\[ \kappa(A)=\frac{\lambda_{\max}}{\lambda_{\min}}. \]

When \(\kappa(A)\) is large, level curves are highly elongated.

Gradient descent may zigzag and converge slowly.

This is a key reason eigenvalues matter in optimization.

A_good = np.array([[2, 0],
                   [0, 1]], dtype=float)

A_bad = np.array([[20, 0],
                  [0, 1]], dtype=float)

plot_quadratic_contours(A_good, "Well-conditioned quadratic")
plot_quadratic_contours(A_bad, "Ill-conditioned quadratic")

22.27 20.25 Python: gradient descent paths

def gradient_descent_quadratic(A, b, x0, alpha, steps):
    x = x0.astype(float).copy()
    path = [x.copy()]
    for _ in range(steps):
        grad = A @ x - b
        x = x - alpha * grad
        path.append(x.copy())
    return np.array(path)

A = np.array([[8, 0],
              [0, 1]], dtype=float)

b = np.array([0, 0], dtype=float)

path = gradient_descent_quadratic(
    A=A,
    b=b,
    x0=np.array([2.0, 2.0]),
    alpha=0.20,
    steps=25
)

x = np.linspace(-2.5, 2.5, 250)
y = np.linspace(-2.5, 2.5, 250)
X, Y = np.meshgrid(x, y)
Z = 0.5 * (A[0,0]*X**2 + A[1,1]*Y**2)

plt.figure(figsize=(6, 6))
cs = plt.contour(X, Y, Z, levels=20)
plt.plot(path[:, 0], path[:, 1], marker="o")
plt.axhline(0, linewidth=0.8)
plt.axvline(0, linewidth=0.8)
plt.grid(True)
plt.axis("equal")
plt.title("Gradient descent path on an elongated quadratic")
plt.show()

22.28 20.26 Quadratic forms and covariance geometry

A covariance matrix \(C\) is symmetric positive semidefinite.

For centered data points \(x_1,\ldots,x_m\), the sample covariance matrix is

\[ C=\frac{1}{m-1}X^TX, \]

where \(X\) is the centered data matrix.

For any vector \(u\),

\[ u^TCu \]

measures variance in direction \(u\).

Eigenvectors of \(C\) identify directions of principal variance.

Eigenvalues measure how much variance occurs in each direction.

This is the geometric basis of PCA.

22.29 20.27 Mahalanobis distance preview

If \(A\) is positive definite, then

\[ \|x\|_A=\sqrt{x^TAx} \]

defines a geometry-dependent length.

The corresponding distance is

\[ d_A(x,y)=\sqrt{(x-y)^TA(x-y)}. \]

When \(A=C^{-1}\) for a covariance matrix \(C\), this is called the Mahalanobis distance.

It measures distance while accounting for different scales and correlations in the data.

Level sets of Mahalanobis distance are ellipses aligned with covariance eigenvectors.

22.30 20.28 Algorithmic summary

NoteAlgorithm: write a quadratic form as a matrix

For a quadratic form:

  1. Put squared-term coefficients on the diagonal.
  2. Split each cross-term coefficient equally across symmetric off-diagonal entries.
  3. Use a symmetric matrix \(A\) so that

\[ q(x)=x^TAx. \]

NoteAlgorithm: classify a quadratic form

Given a symmetric matrix \(A\):

  1. Compute its eigenvalues.
  2. If all are positive, \(A\) is positive definite.
  3. If all are nonnegative, \(A\) is positive semidefinite.
  4. If all are negative, \(A\) is negative definite.
  5. If all are nonpositive, \(A\) is negative semidefinite.
  6. If signs are mixed, \(A\) is indefinite.
NoteAlgorithm: principal axes

Given a symmetric matrix \(A\):

  1. Orthogonally diagonalize

\[ A=QDQ^T. \]

  1. Change variables using

\[ y=Q^Tx. \]

  1. Then

\[ x^TAx=y^TDy. \]

NoteAlgorithm: minimize a positive definite quadratic

For

\[ f(x)=\frac12x^TAx-b^Tx+c \]

with \(A\) positive definite:

  1. Solve

\[ Ax=b. \]

  1. The solution

\[ x_*=A^{-1}b \]

is the unique global minimizer.

22.31 20.29 Common mistakes

22.31.1 Mistake 1: forgetting to split cross terms

The quadratic form

\[ 4x_1x_2 \]

corresponds to off-diagonal entries \(2\) and \(2\), not \(4\) and \(4\).

22.31.2 Mistake 2: using a nonsymmetric matrix unnecessarily

Quadratic forms should be represented by symmetric matrices.

The skew-symmetric part contributes nothing to \(x^TAx\).

22.31.3 Mistake 3: confusing positive entries with positive definiteness

A matrix with positive entries is not necessarily positive definite.

Positive definiteness depends on eigenvalues or equivalent tests.

22.31.4 Mistake 4: thinking determinant alone classifies all quadratic forms

For \(2\times 2\) matrices, determinant helps, but in general eigenvalues give the clearest classification.

22.31.5 Mistake 5: assuming every critical point is a minimum

If the Hessian is indefinite, the critical point is a saddle.

22.31.6 Mistake 6: ignoring conditioning

A positive definite quadratic can still be hard to optimize if its eigenvalues are very uneven.

22.32 20.30 Chapter summary

A quadratic form has the form

\[ q(x)=x^TAx, \]

where \(A\) is symmetric.

For

\[ A= \begin{bmatrix} a&b\\ b&c \end{bmatrix}, \]

we have

\[ x^TAx=ax_1^2+2bx_1x_2+cx_2^2. \]

By the spectral theorem,

\[ A=QDQ^T. \]

With

\[ y=Q^Tx, \]

the quadratic form becomes

\[ x^TAx=y^TDy=\lambda_1y_1^2+\cdots+\lambda_ny_n^2. \]

Eigenvalues classify the quadratic form.

Positive definite matrices produce bowls and ellipses.

Indefinite matrices produce saddles and hyperbolas.

For a quadratic function

\[ f(x)=\frac12x^TAx-b^Tx+c, \]

the gradient is

\[ \nabla f(x)=Ax-b. \]

If \(A\) is positive definite, the unique minimizer solves

\[ Ax=b. \]

Least squares is a quadratic optimization problem with Hessian \(A^TA\).

Quadratic forms connect geometry, optimization, covariance, PCA, and machine learning.

22.33 Exercises

22.33.1 A. Matrix form of quadratic forms

Write each quadratic form as \(x^TAx\) with \(A\) symmetric.

\[ q(x_1,x_2)=3x_1^2+2x_2^2 \]

\[ q(x_1,x_2)=5x_1^2-6x_1x_2+2x_2^2 \]

\[ q(x_1,x_2)=x_1^2+4x_1x_2+x_2^2 \]

\[ q(x_1,x_2,x_3)=x_1^2+2x_2^2+3x_3^2+4x_1x_3 \]

22.33.2 B. Classification

Classify each symmetric matrix as positive definite, positive semidefinite, negative definite, negative semidefinite, or indefinite.

\[ \begin{bmatrix} 4&0\\ 0&1 \end{bmatrix} \]

\[ \begin{bmatrix} 1&0\\ 0&0 \end{bmatrix} \]

\[ \begin{bmatrix} 1&0\\ 0&-1 \end{bmatrix} \]

\[ \begin{bmatrix} 2&1\\ 1&2 \end{bmatrix} \]

\[ \begin{bmatrix} 1&2\\ 2&1 \end{bmatrix} \]

22.33.3 C. Principal axes

For

\[ A= \begin{bmatrix} 2&1\\ 1&2 \end{bmatrix}, \]

  1. Find eigenvalues and orthonormal eigenvectors.
  2. Form \(Q\) and \(D\).
  3. Verify that \(A=QDQ^T\).
  4. Write \(x^TAx\) in the coordinates \(y=Q^Tx\).

22.33.4 D. Optimization

For each quadratic function, find the critical point and classify it.

\[ f(x)=\frac12x^T \begin{bmatrix} 2&0\\ 0&4 \end{bmatrix} x- \begin{bmatrix} 2\\ 8 \end{bmatrix}^Tx \]

\[ f(x)=\frac12x^T \begin{bmatrix} 1&0\\ 0&-1 \end{bmatrix} x \]

\[ f(x)=\frac12x^T \begin{bmatrix} 3&1\\ 1&2 \end{bmatrix} x- \begin{bmatrix} 1\\ 2 \end{bmatrix}^Tx \]

22.33.5 E. Least squares as quadratic optimization

Let

\[ A= \begin{bmatrix} 1&1\\ 1&2\\ 1&3 \end{bmatrix}, \qquad b= \begin{bmatrix} 1\\ 2\\ 2 \end{bmatrix}. \]

  1. Write

\[ f(x)=\frac12\|Ax-b\|^2 \]

in the form

\[ \frac12x^THx-g^Tx+c. \]

  1. Identify \(H\) and \(g\).
  2. Solve \(Hx=g\).
  3. Compare with the least-squares solution.

22.33.6 F. Gradient descent

For

\[ f(x)=\frac12x^TAx \]

with

\[ A= \begin{bmatrix} 8&0\\ 0&1 \end{bmatrix}, \]

  1. Find the eigenvalues of \(A\).
  2. Determine a range of step sizes \(\alpha\) for convergence.
  3. Run gradient descent from \(x_0=(2,2)\).
  4. Plot the path over contour curves.

22.33.7 G. Python exercises

  1. Write a function that plots level curves of a \(2\times 2\) quadratic form.
  2. Write a function that classifies a symmetric matrix by eigenvalues.
  3. Generate positive definite matrices and plot their ellipses.
  4. Generate indefinite matrices and plot their saddle contours.
  5. Visualize gradient descent on well-conditioned and ill-conditioned quadratics.
  6. Compute the covariance matrix of a data set and plot its principal axes.
  7. Explore how eigenvalues affect ellipse shape.

22.33.8 H. Reflection

Write a short paragraph answering each question.

  1. Why do symmetric matrices naturally define quadratic forms?
  2. Why do eigenvectors give principal axes?
  3. Why do positive eigenvalues create bowls and ellipses?
  4. Why do mixed eigenvalue signs create saddle geometry?
  5. How do quadratic forms connect linear algebra to optimization and AI?

22.34 AI-age connection

Quadratic forms are the local geometry of optimization. Near a minimum, many complicated loss functions look approximately quadratic, and the Hessian determines curvature. In least squares, the entire objective is quadratic. In machine learning, eigenvalues of curvature matrices influence conditioning, convergence speed, and stability. Covariance matrices and PCA use positive semidefinite quadratic geometry to identify principal directions of data. Quadratic forms are therefore a bridge from linear algebra to optimization, statistics, and AI.