Get the Outer Product of an array with vector of letters in Python

PythonNumpyServer Side ProgrammingProgramming

Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product is −

[[a0*b0 a0*b1 ... a0*bN ]
[a1*b0 .
[ ... .
[aM*b0     aM*bN ]]

To get the Outer product of an array with vector of letters, use the numpy.outer() method in Python. The 1st parameter a is the first input vector. Input is flattened if not already 1-dimensional. The 2nd parameter b is the second input vector. Input is flattened if not already 1-dimensional. The 3rd parameter out is a location where the result is stored

Steps

At first, import the required libraries −

import numpy as np

Creating two numpy One-Dimensional arrays using the array() method. The 1st array is a vector of letters. The 2nd array is an integer array −

arr1 = np.array(['p', 'q', 'r', 's'], dtype=object)
arr2 = np.array([2, 3, 1, 3])

Display the arrays −

print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

Check the Dimensions of both the arrays −

print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

Check the Shape of both the arrays −

print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

To get the Outer product of an array with vector of letters, use the numpy.outer() method −

print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))

Example

import numpy as np

# Creating two numpy One-Dimensional arrays using the array() method
# The 1st array is a vector of letters
# The 2nd array is an integer array
arr1 = np.array(['p', 'q', 'r', 's'], dtype=object)
arr2 = np.array([2, 3, 1, 3])

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# To get the Outer product of an array with vector of letters, use the numpy.outer() method in Python
print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))

Output

Array1...
['p' 'q' 'r' 's']

Array2...
[2 3 1 3]

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(4,)

Shape of Array2...
(4,)

Result (Outer Product)...
[['pp' 'ppp' 'p' 'ppp']
['qq' 'qqq' 'q' 'qqq']
['rr' 'rrr' 'r' 'rrr']
['ss' 'sss' 's' 'sss']]
raja
Updated on 02-Mar-2022 07:40:12

Advertisements