NumPy np.outer()
You can learn more about the outer product in the resource below:
https://en.wikipedia.org/wiki/Outer_product
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:
[a1*b0 .
[ ... .
[aM*b0 aM*bN ]]
Let us learn how to use the outer() function in NumPy.
Function Syntax
The function syntax can be expressed as shown in the code snippet below:
Parameters
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).
Return Value
The function returns the outer product of the two vectors in the for:
Example #1
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])
print(np.outer(a, b))
The resulting array is as shown:
[20 40 60]
[30 60 90]]
Example #2
In the case of a 2×3 matrix, the function should return:
b = np.array([[1,2,3], [4,5,6]])
print(np.outer(a,b))
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]]
Example #3
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])
print(np.outer(a,b))
The code above should return:
['' 'b' 'bb' 'bbb']
['' 'c' 'cc' 'ccc']
['' 'd' 'dd' 'ddd']]
Conclusion
This article guides you in calculating the outer products of two vectors using NumPy’s outer() function.
Thanks for reading & Happy coding!!
Source: linuxhint.com