NumPy Matrix Operations in Python (with Examples)

NumPy matrix operations work on plain 2D arrays. Multiply matrices with @, transpose with .T, and use np.linalg for inverses, determinants and solutions:

import numpy as np
A = np.array([[2, 1], [1, 3]])
A @ A, A.T, np.linalg.inv(A), np.linalg.det(A)

In this tutorial, I’ll show you the NumPy matrix operations you’ll actually use, on one small sales dataset.

Every example ran on Python 3.12.5 and NumPy 2.5.3.

Create a NumPy matrix with np.array()

Our running sample is units sold at three coffee shops (rows) for three items (columns). Pass a nested list to np.array(); making a matrix in Python covers other ways to build one:

import numpy as np

# units sold: rows = Austin, Denver, Seattle
# columns = latte, muffin, sandwich
units = np.array([[12, 30, 8],
                  [20, 15, 10],
                  [9, 22, 14]])
print(units.shape, units.ndim)
print(np.eye(3, dtype=int))

Output:

(3, 3) 2
[[1 0 0]
 [0 1 0]
 [0 0 1]]

Shape (3, 3) means 3 rows and 3 columns; np.eye() builds an identity matrix. More in the NumPy 2D array guide.

Add and multiply NumPy matrices element by element

Add week 2. +, - and * work cell by cell, so shapes must match:

import numpy as np

week1 = np.array([[12, 30, 8], [20, 15, 10], [9, 22, 14]])
week2 = np.array([[15, 28, 9], [18, 20, 12], [11, 25, 13]])

print(week1 + week2)       # total units per shop and item
print(week1 * week2)       # element-wise, NOT matrix product

Output:

[[27 58 17]
 [38 35 22]
 [20 47 27]]
[[180 840  72]
 [360 300 120]
 [ 99 550 182]]
VS Code output of NumPy matrix addition and element-wise multiplication
Both results keep the 3 by 3 shape.

week1 * week2 gives 12 × 15, 30 × 28 and so on, not a matrix product. For one number, see multiplying an array by a scalar.

How do you multiply two matrices in NumPy?

Use @ (or np.matmul()). Units times a price vector gives each shop’s revenue:

import numpy as np

units = np.array([[12, 30, 8], [20, 15, 10], [9, 22, 14]])
prices = np.array([4.75, 3.25, 8.50])        # USD

revenue = units @ prices
for shop, total in zip(["Austin", "Denver", "Seattle"], revenue):
    print(f"{shop:8} ${total:,.2f}")

print(np.array_equal(revenue, np.dot(units, prices)))

try:
    units @ np.array([4.75, 3.25])
except ValueError as err:
    print("ValueError:", str(err)[:60])

Output:

Austin   $222.50
Denver   $228.75
Seattle  $233.25
True
ValueError: matmul: Input operand 1 has a mismatch in its core dimension
VS Code output of NumPy matrix multiplication with the @ operator giving revenue per shop
Revenue per shop, then a shape mismatch ValueError.

np.dot() matches it for 2D arrays. The inner sizes must match, so (3, 3) needs 3 prices. The vector case is in the Python dot product guide.

Transpose a matrix with .T

.T swaps rows and columns, so our shops-by-items matrix becomes items-by-shops:

import numpy as np

units = np.array([[12, 30, 8], [20, 15, 10], [9, 22, 14]])
by_item = units.T                     # rows are now items
print(by_item)

Output:

[[12 20  9]
 [30 15 22]
 [ 8 10 14]]

Row 2 is now muffins: 30, 15 and 22. It’s a view, not a copy. See transposing an array in Python for 3D axes.

NumPy matrix inverse, determinant and linalg.solve()

Say three orders cost $12.75, $19.75 and $21.75 and you know what was in each. np.linalg.solve() finds the price of each item:

import numpy as np

# lattes, muffins, sandwiches per order
orders = np.array([[2, 1, 0], [1, 2, 1], [1, 0, 2]])
totals = np.array([12.75, 19.75, 21.75])

print("det:", round(np.linalg.det(orders), 2))
prices = np.linalg.solve(orders, totals)
print("prices:", prices)
inv = np.linalg.inv(orders)
print(np.allclose(orders @ inv, np.eye(3)))

try:
    np.linalg.inv(np.array([[1, 2], [2, 4]]))
except np.linalg.LinAlgError as err:
    print("LinAlgError:", err)

Output:

det: 7.0
prices: [4.75 3.25 8.5 ]
True
LinAlgError: Singular matrix
VS Code output of NumPy linalg det, matrix_rank, solve and inv recovering item prices
solve() recovers the three item prices; a singular matrix raises LinAlgError.

I prefer solve() to inv(A) @ b; it’s faster and more accurate. Check floats with np.allclose(). There’s more in finding the inverse of a matrix in Python.

Should you still use np.matrix?

No. The NumPy docs say np.matrix is no longer recommended and may be removed. In old code, * means matrix product:

import numpy as np

a = np.array([[1, 2], [3, 4]])
m = np.matrix([[1, 2], [3, 4]])

print(a * a)          # ndarray: element-wise
print(m * m)          # np.matrix: matrix product
print(a @ a)          # ndarray: matrix product, same as m * m

Output:

[[ 1  4]
 [ 9 16]]
[[ 7 10]
 [15 22]]
[[ 7 10]
 [15 22]]
VS Code output comparing NumPy np.matrix multiplication with a 2D ndarray and the @ operator
m * m and a @ a print the same product, and a * a squares each cell.

To convert old code, use np.asarray(m) and swap * for @. If shapes don’t line up, reshape the array first.

Your next NumPy reads:

Frequently asked questions

What is the difference between * and @ in NumPy?

* multiplies cell by cell; @ is matrix multiplication.

Is np.dot the same as np.matmul?

For 2D arrays, yes. For 3D+ arrays they differ.

Why do I get a matmul ValueError?

The first matrix’s columns must equal the second’s rows. Check .shape.

How do I get the identity matrix in NumPy?

Use np.eye(n), for example np.eye(3).

What does LinAlgError: Singular matrix mean?

Its determinant is 0, so it has no inverse. Try np.linalg.pinv().

Where are NumPy’s matrix functions documented?

See Linear algebra (numpy.linalg) in the NumPy docs.