Write Python. Understand every error.

Starting Python in your browser…

NumPy · topic 24 of 25

Matrices and linear algebra

A 1D array can represent a vector and a 2D array a matrix. Be careful to choose the right kind of multiplication:

  • A * B multiplies element by element; the shapes must match or broadcast
  • A @ B (or np.dot(A, B)) is the matrix product from mathematics

For a matrix product the inner sizes must agree: a (n, k) matrix times a (k, m) matrix gives a (n, m) result. Each result element is a row of A combined with a column of B: multiply the pairs and add them up.

A = np.array([[1, 2],
              [3, 4]])
B = np.array([[5, 6],
              [7, 8]])
print(A @ B)
# [[19 22]
#  [43 50]]   because 1*5 + 2*7 = 19, and so on

The dot product of two vectors, u @ v, multiplies matching elements and adds them, giving one number. Multiplying a matrix by a vector gives a vector, which is a neat way to compute many weighted totals at once.

The np.linalg module solves common problems. np.linalg.solve(A, b) finds x in the system A @ x = b, np.linalg.det(A) gives the determinant, and np.linalg.inv(A) the inverse. np.eye(n) is the identity matrix, and A.T the transpose.

# 2x + y = 5
#  x + 3y = 10
A = np.array([[2, 1], [1, 3]])
b = np.array([5, 10])
print(np.linalg.solve(A, b))   # [1. 3.]

Key takeaways

  • A * B multiplies matching elements, while A @ B (or np.dot(A, B)) is the matrix product from mathematics.
  • For a matrix product, the number of columns in A must equal the number of rows in B.
  • np.linalg.det gives the determinant and np.linalg.inv gives the inverse.
  • Multiplying a matrix by the identity matrix leaves it unchanged.

Common mistakes

  • Multiplying matrices whose inner sizes do not match, such as (2, 3) and (2, 3). Read the ValueError guide.
  • Using * when the matrix product is needed.
  • Trying to invert a matrix whose determinant is zero. It has no inverse.

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.