Vector outer product with Einstein summation convention in Python

The outer product of two vectors creates a matrix where each element is the product of corresponding elements from the input vectors. NumPy's einsum() function provides an elegant way to compute outer products using Einstein summation notation.

Understanding Einstein Summation

The Einstein summation convention uses subscripts to specify which dimensions to multiply and sum. For outer products, we use the notation 'i,j' where i and j represent different dimensions that remain separate (no summation).

Basic Outer Product Example

import numpy as np

# Create two vectors
vector1 = np.array([1, 2])
vector2 = np.array([0, 1, 2, 3, 4])

print("Vector 1:", vector1)
print("Vector 2:", vector2)

# Compute outer product using einsum
outer_product = np.einsum('i,j', vector1, vector2)
print("\nOuter Product:")
print(outer_product)
Vector 1: [1 2]
Vector 2: [0 1 2 3 4]

Outer Product:
[[0 1 2 3 4]
 [0 2 4 6 8]]

How It Works

The subscript 'i,j' tells einsum to:

  • Take each element from the first vector (index i)
  • Multiply it with each element from the second vector (index j)
  • Create a 2D matrix with dimensions (len(vector1), len(vector2))

Comparison with np.outer()

import numpy as np

vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5])

# Using einsum
result_einsum = np.einsum('i,j', vector1, vector2)

# Using np.outer
result_outer = np.outer(vector1, vector2)

print("Using einsum:")
print(result_einsum)
print("\nUsing np.outer:")
print(result_outer)
print("\nResults are equal:", np.array_equal(result_einsum, result_outer))
Using einsum:
[[ 4  5]
 [ 8 10]
 [12 15]]

Using np.outer:
[[ 4  5]
 [ 8 10]
 [12 15]]

Results are equal: True

Advanced Example with Different Data Types

import numpy as np

# Create vectors with different shapes
a = np.arange(3) + 1  # [1, 2, 3]
b = np.arange(4) * 0.5  # [0.0, 0.5, 1.0, 1.5]

print("Vector a:", a)
print("Vector b:", b)
print("Shape of a:", a.shape)
print("Shape of b:", b.shape)

# Compute outer product
result = np.einsum('i,j', a, b)
print("\nOuter product shape:", result.shape)
print("Outer product:")
print(result)
Vector a: [1 2 3]
Vector b: [0.  0.5 1.  1.5]
Shape of a: (3,)
Shape of b: (4,)

Outer product shape: (3, 4)
Outer product:
[[0.  0.5 1.  1.5]
 [0.  1.  2.  3. ]
 [0.  1.5 3.  4.5]]

Key Benefits of einsum

Method Readability Flexibility Performance
einsum('i,j', a, b) High (explicit notation) Very High Optimized
np.outer(a, b) High (clear purpose) Limited to outer product Optimized
a[:, None] * b Medium Medium Good

Conclusion

Einstein summation with np.einsum('i,j', vector1, vector2) provides a clean and flexible way to compute outer products. The notation clearly shows which dimensions are involved, making it ideal for complex linear algebra operations.

Updated on: 2026-03-26T20:12:21+05:30

673 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements