← Back to NumPy Course | Chapter 7: Linear Algebra | Lesson 5 of 6

Matrix multiplication (@)

The @ operator multiplies matrices the proper linear-algebra way.
Syntax
python
result = a @ b
result = np.matmul(a, b)

Matrix multiplication (@)

Introduced in Python 3.5, @ maps to np.matmul. For 2-D arrays it is the standard row-by-column product. For stacks of matrices it broadcasts over the leading dimensions.

Note: A @ B is clearer than np.dot(A, B) when chaining several products.

Example: Matrix multiplication (@)

python
import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([[0, 1], [1, 0]])
print(A @ B)
print(B @ A)
print(A * B)

# Output:
# [[2 1]
#  [4 3]]
# [[3 4]
#  [1 2]]
# [[0 2]
#  [3 0]]
Related Topics
Common Mistakes
  1. Using * instead of @
  2. Mismatched inner dimensions
  3. Assuming A @ B equals B @ A
Chapter Summary
  • @ is matrix multiplication
  • * is element-wise
  • (m, n) @ (n, p) gives (m, p)
  • Not commutative
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.