Scalar multiplication with Einstein summation convention in Python


To perform scalar multiplication with Einstein summation convention, use the numpy.einsum() method in Python. The 1st parameter is the subscript. It specifies the subscripts for summation as comma separated list of subscript labels. The 2nd parameter is the operands. These are the arrays for the operation.

The einsum() method evaluates the Einstein summation convention on the operands. Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values. In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.

Steps

At first, import the required libraries −

import numpy as np

Create an array using the numpy.arange() and reshape() −

arr = np.arange(6).reshape(2,3)

The val is the scalar −

val = 2

Display the array −

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

Check the Dimensions −

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

Get the Datatype −

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

Get the Shape −

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

To perform scalar multiplication with Einstein summation convention, use the numpy.einsum() method −

print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))

Example

import numpy as np

# Create an array using the numpy.arange() and reshape()
arr = np.arange(6).reshape(2,3)

# 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 perform scalar multiplication with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))

Output

Array...
[[0 1 2]
[3 4 5]]

Datatype of Array...
int64

Dimensions of Array...
2

Shape of Array...
(2, 3)

Result (scalar multiplication)...
[[ 0 2 4]
[ 6 8 10]]

Updated on: 02-Mar-2022

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements