Module 5 · Lesson 4
Eigenvalues & Eigenvectors
For a square matrix A, an eigenvector v is a (nonzero) vector whose
direction doesn’t change when A is applied to it — only its length
scales, by a factor called the eigenvalue λ:
A @ v == λ * v
np.linalg.eig(A) returns (eigenvalues, eigenvectors), where
eigenvectors[:, i] is the eigenvector for eigenvalues[i].
For non-square matrices there’s no eigendecomposition, but there is an
analogous, even more general tool: the Singular Value Decomposition
(np.linalg.svd), which factors any matrix into rotation/scaling
components — useful for things like dimensionality reduction, but outside
the scope of this lesson’s exercises.
A = np.array([[2.0, 0.0], [0.0, 3.0]])
eigenvalues, eigenvectors = np.linalg.eig(A)
print("eigenvalues: ", eigenvalues)
print("eigenvectors:\n", eigenvectors)
v0 = eigenvectors[:, 0]
lam0 = eigenvalues[0]
print("A @ v0: ", A @ v0)
print("lam0 * v0:", lam0 * v0)
print("match:", np.allclose(A @ v0, lam0 * v0))
Output:
eigenvalues: [2. 3.]
eigenvectors:
[[1. 0.]
[0. 1.]]
A @ v0: [2. 0.]
lam0 * v0: [2. 0.]
match: True
Verify an eigenpair
Write is_eigenpair(A, v, lam, tol=1e-8) that returns True if
A @ v is within tol of lam * v (elementwise, via np.allclose),
False otherwise.
💡 Hint
np.allclose(A @ v, lam * v, atol=tol).
✅ Solution
def is_eigenpair(A, v, lam, tol=1e-8):
return np.allclose(A @ v, lam * v, atol=tol)
Dominant eigenvalue
Write dominant_eigenvalue(A) that returns the eigenvalue of A with the
largest absolute value, as a real float (eigenvalues from np.linalg.eig
come back as complex numbers even when the imaginary part is zero — use
.real after picking the right one, or take abs() for comparison and
return the original real part).
💡 Hint
Get eigenvalues from np.linalg.eig(A), use np.argmax(np.abs(eigenvalues)) to find the index of the largest-magnitude one, then take .real.
✅ Solution
def dominant_eigenvalue(A):
eigenvalues, _ = np.linalg.eig(A)
idx = np.argmax(np.abs(eigenvalues))
return eigenvalues[idx].real