Compute the outer product of two given vectors using NumPy in Python


The Outer product of two vectors is the matrix obtained by multiplying each element of the vector A with each element in the vector B. The outer product of the vectors a and b is given as a ⊗ b. The following is the mathematical formula for calculating the outer product.

a ⊗ b = [a[0] * b, a[1] * b, ..., a[m-1] * b]

Where,

  • a, b are the vectors.




  • denotes the element-wise multiplication of two vectors.

The output of the outer product is a matrix in which i and j are the elements of the matrix, where ith row is the vector obtained by multiplying the ith element of the vector ‘a’ by ith element of the vector ‘b’.

Calculating the outer product using Numpy

In Numpy, we have a function named outer() for calculating the outer product of the two vectors.

Syntax

The below is the syntax of the outer() function –

np.outer(array1, array2)

Where,

  • Outer is the function.

  • array1 and array2 are the input arrays.

Example

In the following example we are trying to calculate the outer product of two numpy arrays using the outer() function –

import numpy as np
a = np.array([34,23,90,34])
b = np.array([90,34,43,23])
print("The input arrays:",a,b)
outer_product = np.outer(a,b)
print("The Outer product of the given input arrays:",outer_product) 

Output

The input arrays: [34 23 90 34] [90 34 43 23]
The Outer product of the given input arrays: [[3060 1156 1462 782]
[2070 782 989 529]
[8100 3060 3870 2070]
[3060 1156 1462 782]]

Example

Let’s see another example where we calculate the outer product of 2D arrays using the outer() function –

import numpy as np
a = np.array([[34,23],[90,34]])
b = np.array([[90,34],[43,23]])
print("The input arrays:",a,b)
outer_product = np.outer(a,b)
print("The Outer product of the given input arrays:",outer_product)

Output

Following is the output of the outer product of the two arrays.

The input arrays: [[34 23]
[90 34]] [[90 34]
[43 23]]
The Outer product of the given input arrays: [[3060 1156 1462 782]
[2070 782 989 529]
[8100 3060 3870 2070]
[3060 1156 1462 782]]

Example

Now, let’s try to calculate the outer product of the 3D arrays.

import numpy as np
a = np.array([[[34,23],[90,34]],[[12,5],[14,5]]])
b = np.array([[[90,34],[43,23]],[[1,22],[7,2]]])
print("The input arrays:",a,b)
outer_product = np.outer(a,b)
print("The Outer product of the given input arrays:",outer_product)

Output

The input arrays: [[[34 23]
[90 34]]
[[12 5]
[14 5]]] [[[90 34]
[43 23]]
[[ 1 22]
[ 7 2]]]
The Outer product of the given input arrays: [[3060 1156 1462 782 34 748 238 68]
[2070 782 989 529 23 506 161 46]
[8100 3060 3870 2070 90 1980 630 180]
[3060 1156 1462 782 34 748 238 68]
[1080 408 516 276 12 264 84 24]
[ 450 170 215 115 5 110 35 10]
[1260 476 602 322 14 308 98 28]
[ 450 170 215 115 5 110 35 10]]

Updated on: 07-Aug-2023

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements