How to beginner · 3 min read

How to do matrix multiplication in numpy

Quick answer
Use numpy.dot() or the @ operator to perform matrix multiplication in numpy. Both methods multiply two arrays following linear algebra rules, returning the product matrix.

PREREQUISITES

  • Python 3.8+
  • pip install numpy>=1.21

Setup

Install numpy if not already installed using pip. Import numpy in your Python script to access matrix multiplication functions.

bash
pip install numpy

Step by step

Here is a complete example demonstrating matrix multiplication using numpy.dot() and the @ operator with 2D arrays.

python
import numpy as np

# Define two 2D numpy arrays (matrices)
A = np.array([[1, 2, 3],
              [4, 5, 6]])
B = np.array([[7, 8],
              [9, 10],
              [11, 12]])

# Matrix multiplication using numpy.dot()
result_dot = np.dot(A, B)

# Matrix multiplication using @ operator
result_at = A @ B

print("Result using np.dot():")
print(result_dot)

print("\nResult using @ operator:")
print(result_at)
output
Result using np.dot():
[[ 58  64]
 [139 154]]

Result using @ operator:
[[ 58  64]
 [139 154]]

Common variations

You can also multiply 1D arrays (vectors) with numpy.dot() for dot products. For batch matrix multiplication, use numpy.matmul() or @ with higher-dimensional arrays.

python
import numpy as np

# Dot product of 1D arrays
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])
dot_product = np.dot(v1, v2)
print("Dot product of vectors:", dot_product)

# Batch matrix multiplication with 3D arrays
batch_A = np.array([[[1, 0], [0, 1]],
                    [[2, 1], [1, 2]]])
batch_B = np.array([[[4, 1], [2, 2]],
                    [[0, 1], [1, 0]]])

batch_result = np.matmul(batch_A, batch_B)
print("\nBatch matrix multiplication result:")
print(batch_result)
output
Dot product of vectors: 32

Batch matrix multiplication result:
[[[4 1]
  [2 2]]

 [[1 2]
  [2 1]]]

Troubleshooting

If you get a ValueError about shapes not aligned, verify that the number of columns in the first matrix equals the number of rows in the second matrix. Use array.shape to check dimensions.

python
import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6, 7]])  # Shape (1, 3), incompatible

try:
    result = np.dot(A, B)
except ValueError as e:
    print("Error:", e)
    print("A shape:", A.shape)
    print("B shape:", B.shape)
    print("Ensure A's columns equal B's rows for multiplication.")
output
Error: shapes (2,2) and (1,3) not aligned: 2 (dim 1) != 1 (dim 0)
A shape: (2, 2)
B shape: (1, 3)
Ensure A's columns equal B's rows for multiplication.

Key Takeaways

  • Use numpy.dot() or @ for matrix multiplication in numpy.
  • Matrix dimensions must align: columns of first matrix equal rows of second.
  • For batch operations, use numpy.matmul() with higher-dimensional arrays.
Verified 2026-04
Verify ↗