Get the Outer product of an array and a scalar in Python


To get the Outer product of an array and a scalar, 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.

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 ]]

Steps

At first, import the required libraries −

import numpy as np

Create an array using numpy.eye(). This method returns a 2-D array with ones on the diagonal and zeros elsewhere −

arr = np.eye(2)

The val is the scalar −

val = 2

Display the array −

print("Array...\n",arr)

Check the datatype −

print("\nDatatype of Array...\n",arr.dtype)

Check the Dimension −

print("\nDimensions of Array...\n",arr.ndim)

Check the Shape −

print("\nShape of Array...\n",arr.shape)

To get the Outer product of an array and a scalar, use the numpy.outer() method in Python −

print("\nResult (Outer Product)...\n",np.outer(arr, val))

Example

import numpy as np

# Create an array using numpy.eye(). This method returns a 2-D array with ones on the diagonal and zeros elsewhere.
arr = np.eye(2)

# The val is the scalar
val = 2

# Display the array
print("Array...\n",arr)

# Check the datatype
print("\nDatatype of Array...\n",arr.dtype)

# Check the Dimensions
print("\nDimensions of Array...\n",arr.ndim)

# Check the Shape
print("\nShape of Array...\n",arr.shape)

# To get the Outer product of an array and a scalar, use the numpy.outer() method in Python
print("\nResult (Outer Product)...\n",np.outer(arr, val))

Output

Array...
[[1. 0.]
[0. 1.]]

Datatype of Array...
float64

Dimensions of Array...
2

Shape of Array...
(2, 2)

Result (Outer Product)...
[[2.]
[0.]
[0.]
[2.]]

Updated on: 02-Mar-2022

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements