0PricingLogin
Pandas & NumPy Academy · Lesson

Matrix Multiplication with np.matmul and @

Multiply matrices correctly with np.matmul and the @ operator, distinguish element-wise * from true matrix multiplication.

Why Matrix Multiplication Matters

Matrix multiplication is at the heart of data science and machine learning. It underpins neural networks, dimensionality reduction, and linear transformations. In Python, NumPy gives you two clean ways to multiply matrices: the np.matmul() function and the @ operator introduced in Python 3.5. Both are fast, vectorized, and far more efficient than nested Python loops.

The Rules of Matrix Multiplication

For two matrices A and B, the product A @ B is valid only when the number of columns in A equals the number of rows in B. If A is shape (m, n) and B is shape (n, k), the result is shape (m, k). This rule is called the inner-dimension constraint and applies regardless of which NumPy function you use.

import numpy as np
A = np.array([[1, 2], [3, 4]])   # shape (2, 2)
B = np.array([[5, 6], [7, 8]])   # shape (2, 2)
C = A @ B
print(C)  # [[19 22] [43 50]]

All lessons in this course

  1. Matrix Multiplication with np.matmul and @
  2. Determinants, Inverses, and Transposes
  3. Solving Linear Systems
  4. Eigenvalues and SVD Overview
← Back to Pandas & NumPy Academy