Python

NumPy np.outer()

In NumPy, the outer() function allows us to calculate the outer product of two vectors.

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:

[[a0*b0  a0*b1 ... a0*bN ]
 [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:

numpy.outer(a, b, out=None)

Parameters

The function has a simple syntax and accepts three main parameters:

  1. a – refers to the first input vector. Think of it as M in the previous explanation.
  2. b – refers to the second input vector. In this case, it acts as N.
  3. 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:

out[i, j] = a[i] * b[j]

Example #1

The code below shows how to calculate the outer product of two one-dimensional arrays.

# import numpy
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:

[[10 20 30]
 [20 40 60]
 [30 60 90]]

Example #2

In the case of a 2×3 matrix, the function should return:

a = np.array([[10,20,30], [40,50,60]])
b = np.array([[1,2,3], [4,5,6]])
print(np.outer(a,b))

The function should return:

[[ 10  20  30  40  50  60]
 [ 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:

a = np.array(['a', 'b', 'c', 'd'], dtype=object)
b = np.array([0,1,2,3])
print(np.outer(a,b))

The code above should return:

[['' 'a' 'aa' 'aaa']
 ['' '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!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list