TExcelTAD
Home › Linear Algebra & Matrix Theory › Linear Algebra Exercises

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-kk approximation, Eckart–Young

Exercise 1: Solve a system exactly

Solve x+2y−z=3x + 2y - z = 3, 2x+5y+z=122x + 5y + z = 12, −x−y+3z=5-x - y + 3z = 5 by row reducing the augmented matrix (Gauss-Jordan Elimination). The starter prints the matrix without reducing it.

python · try it yourself
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:

text
pivots: (0, 1, 2)
[1, 0, 0, -23]
[0, 1, 0, 12]
[0, 0, 1, -2]

So x=−23x = -23, y=12y = 12, z=−2z = -2: three pivots, a unique solution. Check the first equation: −23+24+2=3-23 + 24 + 2 = 3.

Hint: M.rref() returns a pair (matrix, pivot_columns).

Solution
python · try it yourself
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 v=(4,3,2)\mathbf{v} = (4, 3, 2) onto u=(1,1,0)\mathbf{u} = (1, 1, 0), give the perpendicular remainder and the angle between v\mathbf{v} and u\mathbf{u} in degrees (The Dot Product, Orthogonal Projections).

python · try it yourself
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:

text
proj: [3.5 3.5 0. ]  perp: [ 0.5 -0.5  2. ]  perp·u = 0.0
angle = 23.20 degrees
Solution
python · try it yourself
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 3×33 \times 3 homogeneous matrix for the whole chain (Graphics Transforms). The starter multiplies in the wrong order.

python · try it yourself
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:

text
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
python · try it yourself
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 AA, BB, CC as 12⋅det⁡[B−A,C−A]\frac{1}{2} \cdot \det[B - A, C - A], and report whether the vertices go counter-clockwise (Determinants).

python · try it yourself
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:

text
((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
Solution
python · try it yourself
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

F=[1110]F = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix} satisfies Fn=[F(n+1)F(n)F(n)F(n−1)]F^n = \begin{bmatrix} F(n+1) & F(n) \\ F(n) & F(n-1) \end{bmatrix}. Diagonalize F=PDP−1F = PDP^{-1} in SymPy and compute Fn=PDnP−1F^n = PD^nP^{-1} symbolically (Diagonalization, Solving Recurrences).

python · try it yourself
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:

text
eigenvalues: [1/2 - sqrt(5)/2, 1/2 + sqrt(5)/2]
F(10), F(20), F(30): 55 6765 832040

The eigenvalues are (1±5)/2(1 \pm \sqrt{5})/2; the larger one is the golden ratio φ≈1.618\varphi \approx 1.618, which is why F(n)F(n) grows like φn/5\varphi^n/\sqrt{5}.

Solution
python · try it yourself
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 AA, check A⋅v=0A \cdot \mathbf{v} = \mathbf{0} for each basis vector, and confirm rank+nullity=number of columns\text{rank} + \text{nullity} = \text{number of columns} (Column Space, Row Space and Null Space).

python · try it yourself
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:

text
[-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
python · try it yourself
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 QQ with orthonormal columns spanning the same space as the columns of AA (The Gram-Schmidt Procedure). The starter only normalizes.

python · try it yourself
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:

text
Q^T Q =
 [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
R upper triangular: True   QR = A: True
Solution

This is the modified Gram-Schmidt: each projection uses the current u, which is more stable in floating point.

python · try it yourself
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 y=c0+c1ty = c_0 + c_1 t to the measurements below with the normal equations ATAc=ATyA^T A\mathbf{c} = A^T\mathbf{y}, and compare with np.linalg.lstsq (Least Squares).

python · try it yourself
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:

text
normal equations: [1.081  1.9743]   lstsq: [1.081  1.9743]
sum of squared residuals: 0.0968
Solution
python · try it yourself
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 λ\lambda with the Rayleigh quotient xTAx\mathbf{x}^T A\mathbf{x} (PageRank and Markov Chains).

python · try it yourself
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:

text
lambda ≈ 4.732051   x ≈ [0.7887 0.5774 0.2113]
eigvalsh max: 4.732051

The exact value is 3+33 + \sqrt{3}.

Solution
python · try it yourself
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-kk approximation of a ratings-like matrix for k=1,2,3k = 1, 2, 3 and check the Eckart–Young error formula ∥A−Ak∥F=σk+12+⋯\lVert A - A_k \rVert_F = \sqrt{\sigma_{k+1}^2 + \cdots} (Low-Rank Approximation).

python · try it yourself
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:

text
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

Two "taste" directions (one per group of similar columns) explain almost everything, which is the idea behind the recommender in the mini project.

Solution
python · try it yourself
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?

  1. Translations are always applied first
  2. With column vectors, the right-most matrix acts first, and the translation should act last
  3. Matrix multiplication is commutative
  4. Homogeneous matrices must be sorted alphabetically

In Exercise 6, the rank is 2 and AA has 5 columns. How many vectors does a null space basis have?

  1. 2
  2. 3
  3. 5
  4. 0

In Exercise 9, what happens if the starting vector is exactly orthogonal to the dominant eigenvector?

  1. Nothing; it still converges to it in exact arithmetic
  2. In exact arithmetic it never finds it (rounding errors usually rescue it in practice)
  3. The iteration divides by zero
  4. It converges faster