Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 49 ยท Linear Algebra

The Legacy np.matrix Class and Why to Avoid It

Compare np.matrix with ndarray: operator differences for * and **, always-2D behaviour, shape surprises, and how to migrate old matrix code to arrays and the @ operator.

If you read older NumPy books, forum answers or university notes, you will see np.matrix or np.mat. A matrix looks like a convenient way to do linear algebra, because * means matrix multiplication and **-1 means the inverse, just like on paper. The NumPy team now discourages it: the class is on a path to removal, and it causes surprising bugs when mixed with ordinary arrays.

This lesson shows how matrix differs from ndarray, why those differences hurt, and how to translate old code to modern NumPy. It assumes you know matrix multiplication with @ and the basics of matrices. You do not need to use np.matrix in new code; the aim is to recognise it and replace it safely.

What a matrix is

np.matrix is a subclass of ndarray that is always exactly two-dimensional. Creating one from a 1-D list gives a single row, and slicing a row or column keeps the second dimension. Many operators are redefined.

Python matrix versus ndarray

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The surprises

Each convenience has a cost.

1. * changes meaning. Code that does x * y is correct for a matrix and wrong for an array, and the two look identical. Moving a function between the two worlds silently changes its results.

2. Always 2-D. Indexing a matrix never returns a 1-D array. Reducing functions keep two dimensions as well, so m.sum(axis=0) is a (1, n) matrix, not a plain vector. Code written for arrays that expects (n,) breaks.

3. Mixed types. Combining a matrix and an array gives a matrix, and the result type depends on the order of operands in ways that are easy to forget.

4. No higher dimensions. There is no 3-D matrix, so a feature that works for arrays (batched products with @, einsum, broadcasting over a leading axis) cannot be used.

5. Library support is poor. Many libraries expect ndarray and either convert matrices (losing the type) or misbehave.

Python Shape surprises in practice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Migrating to ndarray

Replace each matrix idiom with its array equivalent.

Old matrix code Modern ndarray code
np.matrix([[1, 2], [3, 4]]) or np.mat(...) np.array([[1, 2], [3, 4]])
A * B (matrix product) A @ B
np.multiply(A, B) (elementwise) A * B
A ** 2 (matrix power) np.linalg.matrix_power(A, 2)
A.I np.linalg.inv(A), or better np.linalg.solve(A, b)
A.T, A.H A.T, A.conj().T
A.A (as array) already an array
A.getA1() (flat array) A.ravel()
np.matrix("1 2; 3 4") np.array([[1, 2], [3, 4]])
np.asmatrix(x) np.asarray(x) and reshape to 2-D if needed

If a function receives a vector and you need a column, write it explicitly with v[:, None] or v.reshape(-1, 1). If you must call old code that returns a matrix, convert at the boundary with np.asarray(result).

Python The same calculation in both styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the array version needs no special class and no inverse. The @ operator gives the clarity that matrix was invented for, without any of the side effects. For why you should solve instead of invert, see Solving Linear Systems.

SciPy's sparse matrices have a similar * convention for the older *_matrix classes, while the newer *_array classes follow NumPy rules. See Sparse Matrices with SciPy and NumPy.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. For two np.matrix objects m and n, what does m * n compute?

    np.matrix redefines * as matrix multiplication. This is the main source of confusion, since the same expression is elementwise for ndarray.
  2. 2. What shape does m[0] have for a (2, 3) np.matrix m?

    A matrix is always two-dimensional, so indexing a row keeps a row shape of (1, 3). An ndarray would return (3,).
  3. 3. Which is the modern replacement for A.I in new code that needs to solve A x = b?

    np.linalg.solve is faster and numerically safer than forming an explicit inverse, and it works on plain arrays.
  4. 4. How do you write the matrix product of two ndarrays a and b?

    The @ operator (np.matmul) is the standard matrix product for arrays. a * b is elementwise.

Summary

  • np.matrix is an always-2-D subclass of ndarray where * is matrix multiplication and ** is matrix power.
  • It breaks array code through shape changes, silent type leaks and a different meaning of *; it cannot be higher than 2-D.
  • Use ndarray with @, np.linalg.matrix_power, np.linalg.solve and np.linalg.inv instead.
  • Convert old results at the boundary with np.asarray, and make column vectors explicit with reshape(-1, 1).

Next: Solving Linear Systems and Least Squares.