Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get the Outer product of two arrays in Python
To get the outer product of two arrays, use the numpy.outer() method in Python. The outer product takes two vectors and produces a matrix where each element is the product of corresponding elements from both vectors.
Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product is ?
[[a0*b0 a0*b1 ... a0*bN ] [a1*b0 a1*b1 ... a1*bN ] [ ... ... ... ... ] [aM*b0 aM*b1 ... aM*bN ]]
Syntax
numpy.outer(a, b, out=None)
Parameters
- a ? First input vector (flattened if not 1-dimensional)
- b ? Second input vector (flattened if not 1-dimensional)
- out ? Optional location where the result is stored
Example
Let's create two arrays and calculate their outer product ?
import numpy as np
# Creating two numpy arrays
arr1 = np.array([5, 10, 15])
arr2 = np.array([20, 25, 30])
# Display the arrays
print("Array1:")
print(arr1)
print("\nArray2:")
print(arr2)
# Check dimensions and shapes
print("\nDimensions of Array1:", arr1.ndim)
print("Dimensions of Array2:", arr2.ndim)
print("Shape of Array1:", arr1.shape)
print("Shape of Array2:", arr2.shape)
# Calculate outer product
result = np.outer(arr1, arr2)
print("\nOuter Product:")
print(result)
Array1: [ 5 10 15] Array2: [20 25 30] Dimensions of Array1: 1 Dimensions of Array2: 2 Shape of Array1: (3,) Shape of Array2: (3,) Outer Product: [[100 125 150] [200 250 300] [300 375 450]]
How It Works
The outer product creates a matrix where each element (i,j) equals arr1[i] * arr2[j] ?
import numpy as np
arr1 = np.array([2, 3])
arr2 = np.array([4, 5, 6])
result = np.outer(arr1, arr2)
print("Result shape:", result.shape)
print("Outer product:")
print(result)
# Manual calculation to show the concept
print("\nManual calculation:")
for i in range(len(arr1)):
for j in range(len(arr2)):
print(f"arr1[{i}] * arr2[{j}] = {arr1[i]} * {arr2[j]} = {arr1[i] * arr2[j]}")
Result shape: (2, 3) Outer product: [[ 8 10 12] [12 15 18]] Manual calculation: arr1[0] * arr2[0] = 2 * 4 = 8 arr1[0] * arr2[1] = 2 * 5 = 10 arr1[0] * arr2[2] = 2 * 6 = 12 arr1[1] * arr2[0] = 3 * 4 = 12 arr1[1] * arr2[1] = 3 * 5 = 15 arr1[1] * arr2[2] = 3 * 6 = 18
Conclusion
The numpy.outer() function efficiently computes the outer product of two vectors, creating a matrix where each element represents the product of corresponding vector elements. This operation is commonly used in linear algebra and mathematical computations.
