0
0
NumpyHow-ToBeginner ยท 3 min read

How to Multiply Matrices Using NumPy in Python

To multiply matrices in NumPy, use the numpy.dot() function or the @ operator for matrix multiplication. Both methods perform the dot product of two arrays, which is the standard matrix multiplication.
๐Ÿ“

Syntax

There are two common ways to multiply matrices in NumPy:

  • numpy.dot(a, b): Multiplies two arrays a and b using dot product rules.
  • a @ b: Uses the @ operator introduced in Python 3.5 for matrix multiplication.

Both require that the number of columns in a equals the number of rows in b.

python
import numpy as np

# Using numpy.dot
result = np.dot(a, b)

# Using @ operator
result = a @ b
๐Ÿ’ป

Example

This example shows how to multiply two 2x2 matrices using both numpy.dot() and the @ operator.

python
import numpy as np

# Define two 2x2 matrices
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

# Multiply using numpy.dot
result_dot = np.dot(a, b)

# Multiply using @ operator
result_at = a @ b

print("Result using numpy.dot:")
print(result_dot)
print("\nResult using @ operator:")
print(result_at)
Output
Result using numpy.dot: [[19 22] [43 50]] Result using @ operator: [[19 22] [43 50]]
โš ๏ธ

Common Pitfalls

Common mistakes when multiplying matrices in NumPy include:

  • Trying to multiply arrays with incompatible shapes (e.g., number of columns in the first matrix not equal to number of rows in the second).
  • Using the * operator, which performs element-wise multiplication, not matrix multiplication.
  • Confusing numpy.dot() with element-wise multiplication functions.

Always check matrix dimensions before multiplying.

python
import numpy as np

# Wrong: element-wise multiplication instead of matrix multiplication
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
wrong_result = a * b  # This multiplies elements one by one

# Right: matrix multiplication
right_result = a @ b

print("Wrong result (element-wise):")
print(wrong_result)
print("\nRight result (matrix multiplication):")
print(right_result)
Output
Wrong result (element-wise): [[ 5 12] [21 32]] Right result (matrix multiplication): [[19 22] [43 50]]
๐Ÿ“Š

Quick Reference

OperationSyntaxDescription
Matrix multiplicationnp.dot(a, b)Dot product of two arrays
Matrix multiplicationa @ bMatrix multiplication using @ operator
Element-wise multiplicationa * bMultiplies elements one by one (not matrix multiplication)
โœ…

Key Takeaways

Use np.dot(a, b) or a @ b to multiply matrices in NumPy.
Ensure the number of columns in the first matrix equals the number of rows in the second.
Do not use * for matrix multiplication; it does element-wise multiplication.
The @ operator is a clean and modern way to multiply matrices in Python 3.5+.
Check matrix shapes before multiplying to avoid errors.