You can learn more about the outer product in the resource below:
The outer product can be expressed as shown:
Suppose you have two vectors a and b with the values as shown:
a = [a0, a1, a2…aM]
b = [b0, b1, b2…bN]
The outer product is calculated as shown:
[ ... .
[aM*b0 aM*bN ]]
Let us learn how to use the outer() function in NumPy.
The function syntax can be expressed as shown in the code snippet below:
The function has a simple syntax and accepts three main parameters:
- a – refers to the first input vector. Think of it as M in the previous explanation.
- b – refers to the second input vector. In this case, it acts as N.
- out – an alternative array to store the resulting output. It takes shape (M, N).
The function returns the outer product of the two vectors in the for:
The code below shows how to calculate the outer product of two one-dimensional arrays.
import numpy as np
a = np.array([10,20,30])
b = np.array([1,2,3])
The resulting array is as shown:
[20 40 60]
[30 60 90]]
In the case of a 2×3 matrix, the function should return:
b = np.array([[1,2,3], [4,5,6]])
The function should return:
[ 20 40 60 80 100 120]
[ 30 60 90 120 150 180]
[ 40 80 120 160 200 240]
[ 50 100 150 200 250 300]
[ 60 120 180 240 300 360]]
The outer function also allows you to perform the outer product with a vector of letters.
An example is as shown:
b = np.array([0,1,2,3])
The code above should return:
['' 'b' 'bb' 'bbb']
['' 'c' 'cc' 'ccc']
['' 'd' 'dd' 'ddd']]
This article guides you in calculating the outer products of two vectors using NumPy’s outer() function.
Thanks for reading & Happy coding!!