0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use Dot Product in NumPy: Syntax and Examples

Use numpy.dot(a, b) to calculate the dot product of two arrays a and b. It multiplies corresponding elements and sums them up, useful for vectors and matrices.
๐Ÿ“

Syntax

The basic syntax for the dot product in NumPy is numpy.dot(a, b).

  • a: First input array (vector or matrix).
  • b: Second input array (vector or matrix).
  • The function returns the dot product, which is a scalar for 1D arrays or a matrix for 2D arrays.
python
import numpy as np

result = np.dot(a, b)
๐Ÿ’ป

Example

This example shows the dot product of two 1D arrays (vectors) and two 2D arrays (matrices).

python
import numpy as np

# Dot product of 1D arrays (vectors)
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
vector_dot = np.dot(a, b)

# Dot product of 2D arrays (matrices)
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
matrix_dot = np.dot(A, B)

print('Dot product of vectors:', vector_dot)
print('Dot product of matrices:\n', matrix_dot)
Output
Dot product of vectors: 32 Dot product of matrices: [[19 22] [43 50]]
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Passing arrays with incompatible shapes for matrix multiplication.
  • Confusing element-wise multiplication (*) with dot product (np.dot).
  • Using np.dot on higher-dimensional arrays without understanding broadcasting rules.

Always check array shapes before using np.dot.

python
import numpy as np

# Wrong: incompatible shapes for dot product
try:
    a = np.array([1, 2])
    b = np.array([[1, 2], [3, 4], [5, 6]])
    np.dot(a, b)
except ValueError as e:
    print('Error:', e)

# Right: compatible shapes
b_correct = np.array([[1, 2], [3, 4]])
result = np.dot(a, b_correct)
print('Correct dot product result:', result)
Output
Error: shapes (2,) and (3,2) not aligned: 2 (dim 0) != 3 (dim 0) Correct dot product result: [7 10]
๐Ÿ“Š

Quick Reference

OperationDescriptionExample
Dot product of vectorsSum of element-wise productsnp.dot([1,2,3], [4,5,6]) โ†’ 32
Dot product of matricesMatrix multiplicationnp.dot([[1,2],[3,4]], [[5,6],[7,8]]) โ†’ [[19,22],[43,50]]
Element-wise multiplicationMultiply elements directlynp.array([1,2]) * np.array([3,4]) โ†’ [3,8]
Shape compatibilityInner dimensions must matchShapes (2,) and (2,3) work, (2,) and (3,2) fail
โœ…

Key Takeaways

Use np.dot(a, b) to compute the dot product of vectors or matrices.
Ensure the inner dimensions of arrays match for matrix multiplication.
np.dot returns a scalar for 1D arrays and a matrix for 2D arrays.
Do not confuse dot product with element-wise multiplication.
Check array shapes to avoid ValueError when using np.dot.