Linear Algebra Exercises
Time to practise the whole course. Each exercise has a starter program that runs but doesn't do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Work each problem on paper first for a small case, then let the code do the arithmetic. SymPy gives exact fractions; NumPy gives fast floating-point answers. When the two disagree in the last digits, NumPy is rounding, not wrong.
| # | Exercise | Practises |
|---|---|---|
| 1 | Solve a system exactly | augmented matrix, rref, pivots |
| 2 | Shadow of a vector | dot product, projection, angle |
| 3 | Compose 2D transforms | matrix multiplication, order of transforms |
| 4 | Area with a determinant | determinants, orientation |
| 5 | Fibonacci by diagonalization | eigenvalues, matrix powers |
| 6 | Basis of a null space | null space, rank–nullity |
| 7 | Write Gram-Schmidt | orthonormal bases, QR |
| 8 | Fit a line | least squares, normal equations |
| 9 | Power iteration | dominant eigenvector, Rayleigh quotient |
| 10 | Compress with the SVD | rank- approximation, Eckart–Young |
Exercise 1: Solve a system exactly
Solve , , by row reducing the augmented matrix (Gauss-Jordan Elimination). The starter prints the matrix without reducing it.
from sympy import Matrix
M = Matrix([[1, 2, -1, 3],
[2, 5, 1, 12],
[-1, -1, 3, 5]])
R, pivots = M, () # TODO: use M.rref() to get the reduced matrix and the pivot columns
print("pivots:", pivots)
for row in R.tolist():
print(row)pivots: ()
[1, 2, -1, 3]
[2, 5, 1, 12]
[-1, -1, 3, 5]
Expected output when solved:
pivots: (0, 1, 2)
[1, 0, 0, -23]
[0, 1, 0, 12]
[0, 0, 1, -2]So , , : three pivots, a unique solution. Check the first equation: .
Hint:
M.rref()returns a pair(matrix, pivot_columns).
Solution
from sympy import Matrix
M = Matrix([[1, 2, -1, 3],
[2, 5, 1, 12],
[-1, -1, 3, 5]])
R, pivots = M.rref()
print("pivots:", pivots)
for row in R.tolist():
print(row)pivots: (0, 1, 2)
[1, 0, 0, -23]
[0, 1, 0, 12]
[0, 0, 1, -2]
Exercise 2: Shadow of a vector
Project onto , give the perpendicular remainder and the angle between and in degrees (The Dot Product, Orthogonal Projections).
import numpy as np
v = np.array([4.0, 3.0, 2.0])
u = np.array([1.0, 1.0, 0.0])
proj = np.zeros(3) # TODO: (v·u / u·u) u
perp = v - proj
angle = 0.0 # TODO: arccos(v·u / (|v||u|)) in degrees
print("proj:", proj, " perp:", perp, " perp·u =", float(perp @ u))
print(f"angle = {angle:.2f} degrees")proj: [0. 0. 0.] perp: [4. 3. 2.] perp·u = 7.0
angle = 0.00 degrees
Expected output when solved:
proj: [3.5 3.5 0. ] perp: [ 0.5 -0.5 2. ] perp·u = 0.0
angle = 23.20 degreesSolution
import numpy as np
v = np.array([4.0, 3.0, 2.0])
u = np.array([1.0, 1.0, 0.0])
proj = (v @ u) / (u @ u) * u
perp = v - proj
angle = np.degrees(np.arccos(v @ u / (np.linalg.norm(v) * np.linalg.norm(u))))
print("proj:", proj, " perp:", perp, " perp·u =", float(perp @ u))
print(f"angle = {angle:.2f} degrees")proj: [3.5 3.5 0. ] perp: [ 0.5 -0.5 2. ] perp·u = 0.0
angle = 23.20 degrees
Exercise 3: Compose 2D transforms
A sprite's corner (1, 0) should first be scaled by 2, then rotated 90° counter-clockwise, then moved by (3, 1). Build one homogeneous matrix for the whole chain (Graphics Transforms). The starter multiplies in the wrong order.
import numpy as np
S = np.diag([2.0, 2.0, 1.0])
R = np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
T = np.array([[1.0, 0.0, 3.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]])
M = S @ R @ T # TODO: the transform applied first must be on the right
print("M =\n", M)
print("corner ->", M @ np.array([1.0, 0.0, 1.0]))M =
[[ 0. -2. -2.]
[ 2. 0. 6.]
[ 0. 0. 1.]]
corner -> [-2. 8. 1.]
Expected output when solved:
M =
[[ 0. -2. 3.]
[ 2. 0. 1.]
[ 0. 0. 1.]]
corner -> [3. 3. 1.](1, 0) → scaled (2, 0) → rotated (0, 2) → moved (3, 3).
Solution
import numpy as np
S = np.diag([2.0, 2.0, 1.0])
R = np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
T = np.array([[1.0, 0.0, 3.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]])
M = T @ R @ S
print("M =\n", M)
print("corner ->", M @ np.array([1.0, 0.0, 1.0]))M =
[[ 0. -2. 3.]
[ 2. 0. 1.]
[ 0. 0. 1.]]
corner -> [3. 3. 1.]
Exercise 4: Area with a determinant
Compute the signed area of the triangle with vertices , , as , and report whether the vertices go counter-clockwise (Determinants).
from sympy import Matrix, Rational
def signed_area(A, B, C):
return 0 # TODO: half the determinant of the 2x2 matrix with columns B - A and C - A
for tri in [((0, 0), (4, 0), (0, 3)), ((1, 1), (2, 5), (6, 2)), ((0, 0), (1, 1), (3, 3))]:
a = signed_area(*[Matrix(p) for p in tri])
print(tri, "area", a, "counter-clockwise" if a > 0 else "clockwise" if a < 0 else "degenerate")((0, 0), (4, 0), (0, 3)) area 0 degenerate
((1, 1), (2, 5), (6, 2)) area 0 degenerate
((0, 0), (1, 1), (3, 3)) area 0 degenerate
Expected output when solved:
((0, 0), (4, 0), (0, 3)) area 6 counter-clockwise
((1, 1), (2, 5), (6, 2)) area -19/2 clockwise
((0, 0), (1, 1), (3, 3)) area 0 degenerateSolution
from sympy import Matrix, Rational
def signed_area(A, B, C):
return Rational(1, 2) * Matrix.hstack(B - A, C - A).det()
for tri in [((0, 0), (4, 0), (0, 3)), ((1, 1), (2, 5), (6, 2)), ((0, 0), (1, 1), (3, 3))]:
a = signed_area(*[Matrix(p) for p in tri])
print(tri, "area", a, "counter-clockwise" if a > 0 else "clockwise" if a < 0 else "degenerate")((0, 0), (4, 0), (0, 3)) area 6 counter-clockwise
((1, 1), (2, 5), (6, 2)) area -19/2 clockwise
((0, 0), (1, 1), (3, 3)) area 0 degenerate
Exercise 5: Fibonacci by diagonalization
satisfies . Diagonalize in SymPy and compute symbolically (Diagonalization, Solving Recurrences).
from sympy import Matrix, symbols, simplify
n = symbols("n", integer=True, nonnegative=True)
F = Matrix([[1, 1], [1, 0]])
P, D = Matrix.eye(2), F # TODO: P, D = F.diagonalize()
print("eigenvalues:", [D[0, 0], D[1, 1]])
Fn = P * D**n * P.inv()
fib = lambda k: simplify(Fn[0, 1].subs(n, k))
print("F(10), F(20), F(30):", fib(10), fib(20), fib(30))eigenvalues: [1, 0]
F(10), F(20), F(30): 55 6765 832040
Expected output when solved:
eigenvalues: [1/2 - sqrt(5)/2, 1/2 + sqrt(5)/2]
F(10), F(20), F(30): 55 6765 832040The eigenvalues are ; the larger one is the golden ratio , which is why grows like .
Solution
from sympy import Matrix, symbols, simplify
n = symbols("n", integer=True, nonnegative=True)
F = Matrix([[1, 1], [1, 0]])
P, D = F.diagonalize()
print("eigenvalues:", [D[0, 0], D[1, 1]])
Fn = P * D**n * P.inv()
fib = lambda k: simplify(Fn[0, 1].subs(n, k))
print("F(10), F(20), F(30):", fib(10), fib(20), fib(30))eigenvalues: [1/2 - sqrt(5)/2, 1/2 + sqrt(5)/2]
F(10), F(20), F(30): 55 6765 832040
Exercise 6: Basis of a null space
Find a basis of the null space of , check for each basis vector, and confirm (Column Space, Row Space and Null Space).
from sympy import Matrix
A = Matrix([[1, 2, 0, 1, -1],
[2, 4, 1, 4, 0],
[3, 6, 1, 5, -1]])
basis = [] # TODO: A.nullspace()
for v in basis:
print(list(v), "A v =", list(A * v))
print("rank", A.rank(), "+ nullity", len(basis), "=", A.rank() + len(basis), "columns:", A.cols)rank 2 + nullity 0 = 2 columns: 5
Expected output when solved:
[-2, 1, 0, 0, 0] A v = [0, 0, 0]
[-1, 0, -2, 1, 0] A v = [0, 0, 0]
[1, 0, -2, 0, 1] A v = [0, 0, 0]
rank 2 + nullity 3 = 5 columns: 5(The third row is the sum of the first two, so the rank is only 2.)
Solution
from sympy import Matrix
A = Matrix([[1, 2, 0, 1, -1],
[2, 4, 1, 4, 0],
[3, 6, 1, 5, -1]])
basis = A.nullspace()
for v in basis:
print(list(v), "A v =", list(A * v))
print("rank", A.rank(), "+ nullity", len(basis), "=", A.rank() + len(basis), "columns:", A.cols)[-2, 1, 0, 0, 0] A v = [0, 0, 0]
[-1, 0, -2, 1, 0] A v = [0, 0, 0]
[1, 0, -2, 0, 1] A v = [0, 0, 0]
rank 2 + nullity 3 = 5 columns: 5
Exercise 7: Write Gram-Schmidt
Complete gram_schmidt so that it returns a matrix with orthonormal columns spanning the same space as the columns of (The Gram-Schmidt Procedure). The starter only normalizes.
import numpy as np
def gram_schmidt(A):
Q = np.zeros_like(A)
for j in range(A.shape[1]):
u = A[:, j].copy()
# TODO: subtract the projection of u onto every earlier column Q[:, i]
Q[:, j] = u / np.linalg.norm(u)
return Q
A = np.array([[1.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
Q = gram_schmidt(A)
print("Q^T Q =\n", np.round(Q.T @ Q, 6) + 0)
R = Q.T @ A
print("R upper triangular:", np.allclose(R, np.triu(R)), " QR = A:", np.allclose(Q @ R, A))Q^T Q =
[[1. 0.666667 0.666667]
[0.666667 1. 0.666667]
[0.666667 0.666667 1. ]]
R upper triangular: False QR = A: False
Expected output when solved:
Q^T Q =
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
R upper triangular: True QR = A: TrueSolution
This is the modified Gram-Schmidt: each projection uses the current u, which is more stable in floating point.
import numpy as np
def gram_schmidt(A):
Q = np.zeros_like(A)
for j in range(A.shape[1]):
u = A[:, j].copy()
for i in range(j):
u -= (Q[:, i] @ u) * Q[:, i]
Q[:, j] = u / np.linalg.norm(u)
return Q
A = np.array([[1.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
Q = gram_schmidt(A)
print("Q^T Q =\n", np.round(Q.T @ Q, 6) + 0)
R = Q.T @ A
print("R upper triangular:", np.allclose(R, np.triu(R)), " QR = A:", np.allclose(Q @ R, A))Q^T Q =
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
R upper triangular: True QR = A: True
Exercise 8: Fit a line
Fit to the measurements below with the normal equations , and compare with np.linalg.lstsq (Least Squares).
import numpy as np
t = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([1.1, 2.9, 5.2, 7.1, 8.8, 11.0])
A = np.column_stack([np.ones_like(t), t])
c = np.zeros(2) # TODO: solve the normal equations
c_ref = np.linalg.lstsq(A, y, rcond=None)[0]
print("normal equations:", np.round(c, 4), " lstsq:", np.round(c_ref, 4))
print("sum of squared residuals:", round(float(np.sum((A @ c - y) ** 2)), 4))normal equations: [0. 0.] lstsq: [1.081 1.9743]
sum of squared residuals: 285.51
Expected output when solved:
normal equations: [1.081 1.9743] lstsq: [1.081 1.9743]
sum of squared residuals: 0.0968Solution
import numpy as np
t = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([1.1, 2.9, 5.2, 7.1, 8.8, 11.0])
A = np.column_stack([np.ones_like(t), t])
c = np.linalg.solve(A.T @ A, A.T @ y)
c_ref = np.linalg.lstsq(A, y, rcond=None)[0]
print("normal equations:", np.round(c, 4), " lstsq:", np.round(c_ref, 4))
print("sum of squared residuals:", round(float(np.sum((A @ c - y) ** 2)), 4))normal equations: [1.081 1.9743] lstsq: [1.081 1.9743]
sum of squared residuals: 0.0968
Exercise 9: Power iteration
Find the dominant eigenvalue and eigenvector of a symmetric matrix by repeated multiplication and normalization, and estimate with the Rayleigh quotient (PageRank and Markov Chains).
import numpy as np
A = np.array([[4.0, 1.0, 0.0], [1.0, 3.0, 1.0], [0.0, 1.0, 2.0]])
x = np.ones(3) / np.sqrt(3)
for _ in range(50):
pass # TODO: x = A x, then normalize x to length 1
lam = float(x @ A @ x)
print("lambda ≈", round(lam, 6), " x ≈", np.round(x, 4))
print("eigvalsh max:", round(float(np.linalg.eigvalsh(A)[-1]), 6))lambda ≈ 4.333333 x ≈ [0.5774 0.5774 0.5774]
eigvalsh max: 4.732051
Expected output when solved:
lambda ≈ 4.732051 x ≈ [0.7887 0.5774 0.2113]
eigvalsh max: 4.732051The exact value is .
Solution
import numpy as np
A = np.array([[4.0, 1.0, 0.0], [1.0, 3.0, 1.0], [0.0, 1.0, 2.0]])
x = np.ones(3) / np.sqrt(3)
for _ in range(50):
x = A @ x
x = x / np.linalg.norm(x)
lam = float(x @ A @ x)
print("lambda ≈", round(lam, 6), " x ≈", np.round(x, 4))
print("eigvalsh max:", round(float(np.linalg.eigvalsh(A)[-1]), 6))lambda ≈ 4.732051 x ≈ [0.7887 0.5774 0.2113]
eigvalsh max: 4.732051
Exercise 10: Compress with the SVD
Build the best rank- approximation of a ratings-like matrix for and check the Eckart–Young error formula (Low-Rank Approximation).
import numpy as np
A = np.array([[5, 4, 1, 1, 0], [4, 5, 1, 0, 1], [1, 1, 5, 4, 4],
[0, 1, 4, 5, 5], [5, 5, 0, 1, 1]], dtype=float)
U, s, Vt = np.linalg.svd(A)
print("singular values:", np.round(s, 4))
for k in (1, 2, 3):
Ak = np.zeros_like(A) # TODO: keep the first k singular triplets
err = np.linalg.norm(A - Ak)
print(f"k={k}: error {err:.4f} formula {np.sqrt(np.sum(s[k:] ** 2)):.4f}")singular values: [13.003 9.5063 1.6382 1.3512 0.212 ]
k=1: error 16.2481 formula 9.7429
k=2: error 16.2481 formula 2.1341
k=3: error 16.2481 formula 1.3677
Expected output when solved:
singular values: [13.003 9.5063 1.6382 1.3512 0.212 ]
k=1: error 9.7429 formula 9.7429
k=2: error 2.1341 formula 2.1341
k=3: error 1.3677 formula 1.3677Two "taste" directions (one per group of similar columns) explain almost everything, which is the idea behind the recommender in the mini project.
Solution
import numpy as np
A = np.array([[5, 4, 1, 1, 0], [4, 5, 1, 0, 1], [1, 1, 5, 4, 4],
[0, 1, 4, 5, 5], [5, 5, 0, 1, 1]], dtype=float)
U, s, Vt = np.linalg.svd(A)
print("singular values:", np.round(s, 4))
for k in (1, 2, 3):
Ak = U[:, :k] @ np.diag(s[:k]) @ Vt[:k]
err = np.linalg.norm(A - Ak)
print(f"k={k}: error {err:.4f} formula {np.sqrt(np.sum(s[k:] ** 2)):.4f}")singular values: [13.003 9.5063 1.6382 1.3512 0.212 ]
k=1: error 9.7429 formula 9.7429
k=2: error 2.1341 formula 2.1341
k=3: error 1.3677 formula 1.3677
Test yourself
In Exercise 3, why must the translation matrix be on the left of the product?
- Translations are always applied first
- With column vectors, the right-most matrix acts first, and the translation should act last
- Matrix multiplication is commutative
- Homogeneous matrices must be sorted alphabetically
In Exercise 6, the rank is 2 and has 5 columns. How many vectors does a null space basis have?
- 2
- 3
- 5
- 0
In Exercise 9, what happens if the starting vector is exactly orthogonal to the dominant eigenvector?
- Nothing; it still converges to it in exact arithmetic
- In exact arithmetic it never finds it (rounding errors usually rescue it in practice)
- The iteration divides by zero
- It converges faster