Sub topic 14
Identity, Diagonal, and Symmetric Matrices
This chapter assumes you can index and traverse a nested-list 2D array, and that you know how transpose and matrix multiplication work. Three special matrix shapes show up often. Each one has a simple test and a useful shortcut.
Square matrices and the main diagonal
All three shapes are square, meaning rows equal columns (n by n). Their main diagonal is the set of cells where the row index equals the column index: (0, 0), (1, 1), (2, 2), and so on. Most of the checks below compare each cell's row and column index.
Identity matrix
The identity matrix has 1 on the main diagonal and 0 everywhere else. It plays the role of the number 1 in multiplication: multiplying any compatible matrix by it returns the same matrix.
def identity(n):
return [[1 if r == c else 0 for c in range(n)] for r in range(n)]
def matmul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(len(b)))
for j in range(len(b[0]))] for i in range(len(a))]
A = [[2, 7], [4, 9]]
print(identity(3)) # [[1, 0, 0], [0, 1, 0], [0, 0, 1]], identity(2)) == A) # True
print(matmul(identity(2), A) == A) # TrueThe comprehension builds a fresh listids the shared-row pitfall from earlier in this tutorial.
Diagonal matrix
A diagonal matrix has zeros everywhere off the main diagonal. The diagonal entries can be any value. The identity matrix is a diagonal matrix whose diagonal entries are all 1.
def is_diagonal(m):
return all(m[r][c] == 0
for r in range(len(m))
for c in range(len(m[r]))
if r != c)
D = [[3, 0, 0], [0, 5, 0], [0, 0, 8]]
print(is_diagonal(D)) # True
print(is_diagonal([[1, 2], [0, 1]])) # FalseBecause only n values matter, you can store a diagonal matrix as a 1D list. Multiplying a matrix by it also gets cheaper. Multiplying a diagonal matrix by a vector just scales each element, which costs O(n) instead of O(n²).
diag = [3, 5, 8]
vector = [1, 2, 3]
print([d * v for d, v in zip(diag, vector)]) # [3, 10, 24]Symmetric matrix
A symmetric matrix equals its own transpose: m[r][c] == m[c][r] for every pair of cells. The matrix mirrors across the main diagonal.
def is_symmetric(m):
n = len(m)
if any(len(row) != n for row in m):
return False
return all(m[r][c] == m[c][r]
for r in range(n)
for c in range(r + 1, n))
S = [[1, 7, 3],
[7, 4, 5],
[3, 5, 9]]
print(is_symmetric(S)) # True
print(S == [list(col) for col in zip(*S)]) # True, same test via transpose
print(is_symmetric([[1, 2], [3, 4]])) # FalseThe loop only visits cells above the diagonal (c starts at r + 1). This halves the work, and the diagonal always matches itself. A distance table between cities is a typical symmetric matrix, because the distance from A to B equals the distance from B to A. You can store only one triangle of it and save about half the space.
Every diagonal matrix is symmetric, because its off-diagonal cells are all 0 and so mirror each other. The reverse is not true.
Common errors
- Calling a non-square matrix symmetric. Check the shape first, or
m[c][r]may raise anIndexError. - Checking only that the diagonal is nonzero. A diagonal matrix needs every off-diagonal cell to be zero.
- Building the identity with
[[0] * n] * n. The rows are shared, so setting the diagonal corrupts every row. - Comparing floating-point matrices with
==. Use a tolerance, such asabs(a - b) < 1e-9, for computed values.
Exercise
Write a function is_identity(m) that returns True only when m is a square matrix with 1 on the main diagonal and 0 elsewhere.
Show answer
def is_identity(m): n = len(m) if any(len(row) != n for row in m): return False return all(m[r][c] == (1 if r == c else 0) for r in range(n) for c in range(n))
Exercise
A matrix is symmetric. Its cell at row 2, column 0 holds 9. What does the cell at row 0, column 2 hold, and why?
Show answer
It holds 9, because a symmetric matrix satisfies m[r][c] == m[c][r].