Skip to main content

Understanding numpy.matmul() — Matrix Multiplication Made Simple 🔢

Calculating read time…

Understanding numpy.matmul() — Matrix Multiplication Made Simple 🔢



One operation powers every neural-network layer, recommendation system, and image transform. Here’s exactly what it does — visually and correctly.

A @ B → Result

Matrix A

[ 1 2 ]
[ 3 4 ]
×

Matrix B

[ 5 6 ]
[ 7 8 ]
=

Matrix C

[ 19 22 ]
[ 43 50 ]

1. Row × Column — the core idea

Take first row of A and first column of B:

Row A: [ 1 2 ]   ×   Column B: [ 5 ]
                                      [ 7 ]

(1 × 5) + (2 × 7) = 5 + 14 = 19

→ This becomes C[0,0] = 19

2. Next cell (same pattern)

Same row of A × second column of B:

(1 × 6) + (2 × 8) = 6 + 16 = 22

→ C[0,1] = 22   |   Repeat for every output cell

3. The Shape Rule (must remember)

(m × n) @ (n × p) → (m × p)

Inner dimensions must match. Outer dimensions become the result shape.

✓ (2 × 3) @ (3 × 4) → (2 × 4)

✗ (2 × 3) @ (2 × 4) → shape error

4. NumPy syntax

import numpy as np

C = np.matmul(A, B)
C = A @ B         # preferred modern form

@ is NumPy’s matrix-multiplication operator (Python 3.5+)

5. matmul ≠ element-wise multiply

Matrix multiplication

np.matmul(A, B) or A @ B

row × column → sum → one cell

[[19 22]
[43 50]]

Element-wise

A * B

matching positions multiply

[[ 5 12]
[21 32]]

Completely different results!

6. Quick memory cards

MATMUL
Matrix multiplication
ROW × COLUMN
Core calculation
INNER DIMS
Must match
OUTPUT SHAPE
Outer dimensions

A @ B  →  take a row  →  take a column  →  multiply + add  →  fill one output cell

That is the entire mechanism. Once you see “row × column → one cell”, every matmul call in NumPy (and in every neural network) becomes transparent.

Comments