Definition and Equality
A matrix is a rectangular grid of numbers arranged in rows and columns. This lesson fixes the vocabulary (size, entries, square, identity, zero) and the one rule for when two matrices are equal, and shows how SymPy and NumPy store them.
Rows, columns and entries
An matrix has rows and columns. We name matrices with capital letters and write the entry in row , column as (row first, then column):
The numbers and are the size (or shape) of the matrix. The entries can come from any field: rational or real numbers here, complex numbers later, and integers modulo in Matrix Arithmetic Modulo p. A shorthand for "the matrix whose entries are " is .
Special shapes and special matrices
| Name | Shape / rule | Example |
|---|---|---|
| Row vector | ||
| Column vector | the vectors of Points and Vectors | |
| Square matrix | , , … | |
| Main diagonal | entries | |
| Zero matrix | every entry is 0 | any size |
| Identity matrix (or ) | square, 1 on the diagonal, 0 elsewhere | below |
| Diagonal matrix | square, zero off the diagonal | |
| Upper triangular | zero below the diagonal | the echelon forms of Gaussian Elimination |
You have already met matrices: the augmented matrix of a system of linear equations is exactly such a grid, and row reduction works on it entry by entry.
Equality
Two matrices and are equal, , when
- they have the same size , and
- for every and .
So a matrix is never equal to a matrix, even if they contain the same six numbers, and a row vector is not equal to a column vector. An equation between matrices is really equations between numbers, which is why matrix equations can be solved by comparing entries:
Matrices in SymPy and NumPy
SymPy's Matrix keeps exact rational entries; NumPy's ndarray stores fast floating-point (or integer) numbers. Both index from 0, so the textbook entry is A[0, 1] in code.
from sympy import Matrix, Rational, eye, zeros, diag
B = Matrix([[4, -1, 0],
[2, 5, 7]])
print("shape:", B.shape)
print("b12 (row 1, col 2) =", B[0, 1])
print("b23 (row 2, col 3) =", B[1, 2])
print("row 2:", list(B.row(1)), " column 3:", list(B.col(2)))
print("I3 rows:", eye(3).tolist())
print("zero 2x3:", zeros(2, 3).tolist())
print("diag(2, 5, -1):", diag(2, 5, -1).tolist())
C = Matrix([[Rational(8, 2), -1, 0], [2, 5, 7]]) # 8/2 simplifies to 4
print("B == C:", B == C)
print("B == B.T:", B == B.T) # different shapesshape: (2, 3)
b12 (row 1, col 2) = -1
b23 (row 2, col 3) = 7
row 2: [2, 5, 7] column 3: [0, 7]
I3 rows: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
zero 2x3: [[0, 0, 0], [0, 0, 0]]
diag(2, 5, -1): [[2, 0, 0], [0, 5, 0], [0, 0, -1]]
B == C: True
B == B.T: False
In NumPy, == does not answer "are these matrices equal?". It compares entry by entry and returns a matrix of booleans. Use np.array_equal for exact equality and np.allclose when the entries are floats that went through rounding:
import numpy as np
A = np.array([[0.1 + 0.2, 1.0],
[2.0, 3.0]])
B = np.array([[0.3, 1.0],
[2.0, 3.0]])
print(A == B) # element-wise, not one answer
print("array_equal:", np.array_equal(A, B))
print("allclose: ", np.allclose(A, B))
print("shapes differ:", np.array_equal(np.ones((2, 3)), np.ones((3, 2))))[[False True]
[ True True]]
array_equal: False
allclose: True
shapes differ: False
Tip:
if A == B:on NumPy arrays raises "The truth value of an array with more than one element is ambiguous". The error is NumPy telling you to choosearray_equal,allclose,.all()or.any().
In software
- Images are matrices: a grayscale image is a matrix of brightness values, and a colour image is three of them (or one array).
- Tables of data: a dataset with 10 000 rows and 12 features is a matrix ; machine-learning libraries expect exactly this shape (NumPy and pandas for ML).
- Games and graphics use and matrices for transforms (Matrices and Multiplication).
- Memory layout: RAM is one-dimensional, so an matrix is stored either row after row (row-major, C and NumPy's default) or column after column (column-major, Fortran, MATLAB, GLSL). In row-major order entry lives at offset . Mixing the two conventions silently transposes your matrix.
- Testing: comparing float matrices with exact equality is a classic flaky test; tolerance-based checks (
allclose) are the norm.
Exercises
Exercise 1: Read off entries
For (given row by row), state the size of and the entries , and .
Answer
is ; , , .
Solution
from sympy import Matrix
M = Matrix([[3, 0, -4, 1], [7, 2, 2, 9], [-5, 6, 0, 8]])
print(M.shape, M[1, 3], M[2, 0], M[0, 2])(3, 4) 9 -5 -4
Exercise 2: Solve by equality
Find so that .
Answer
, , , .
Solution
Exercise 3: Can they be equal?
Can a matrix ever equal a matrix? Can a matrix be "equal" to the number 5?
Answer
No to the first (sizes differ). Strictly, is a matrix and 5 is a number, but the two are usually identified, so in practice yes.
Solution
Equality needs the same size first, and , so no entries need to be compared. A matrix has exactly one entry and behaves like that number under all operations, so most texts (and SymPy's Matrix([[5]])[0]) treat them as the same thing; NumPy keeps them distinct (np.array([[5]]).shape is (1, 1), a plain 5 has no shape).
Exercise 4: Build an identity in code
Write a function identity(n) that returns the identity as a list of lists, without NumPy or SymPy, and check it against sympy.eye(4).
Answer
[[1 if i == j else 0 for j in range(n)] for i in range(n)], which equals eye(4).tolist().
Solution
The entry in row , column is 1 exactly when .
from sympy import eye
def identity(n):
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
print(identity(4))
print(identity(4) == eye(4).tolist())[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
True
Exercise 5: Row-major offsets
A matrix is stored row-major in a flat array (0-based). At which offset is the textbook entry ? Which entry is at offset 13?
Answer
is at offset 16; offset 13 holds .
Solution
import numpy as np
A = np.arange(24).reshape(4, 6) # entry value = its flat offset
r, c = np.unravel_index(13, (4, 6))
print(int(A[2, 4]), (int(r), int(c)))16 (2, 1)
Test yourself
In the matrix , what is ?
- -1
- 2
- 0
- 5
When are two matrices A and B equal?
- When they have the same size and every pair of corresponding entries is equal
- When they contain the same numbers in any order
- When they have the same number of entries
- When their diagonals agree
In NumPy, what does A == B return for two float arrays?
- A single True or False
- The number of equal entries
- An error always
- A array of booleans