Home »
Python »
Python Programs
NumPy - Dot product of two arrays of different dimensions
By IncludeHelp Last updated : December 13, 2023
Problem statement
Write a Python program to compute the dot product of two NumPy arrays of different dimensions.
Prerequisites
To understand the given solution, you should know about the following Python topics:
Dot product of two NumPy arrays of different dimensions
To compute the dot product of two NumPy arrays of different dimensions, use the numpy.dot() method, it accepts two NumPy arrays as its arguments and returns the dot product. This method can compute the products of the arrays with different dimensions.
Below is the syntax of numpy.dot() method:
numpy.dot(a, b, out=None)
Here, arguments a and b are the arrays whose dot product we have to find and out is an optional parameter for output arguments.
Python program to compute dot product of two NumPy arrays of different dimensions
Take two NumPy arrays of different dimensions, compute, and print their dot product.
# Importing numpy library
import numpy as np
# Creating two arrays of different dimensions
arr1 = np.array([[10, 20], [30, 40], [11, 22]])
arr2 = np.array([[22, 33], [11, 12]])
# Printing original arrays
print("arr1 is:\n", arr1)
print("arr2 is:\n", arr2)
# Computing the dot product
dotProduct = np.dot(arr1, arr2)
# Printing the result
print("\nDot product of arr1 and arr2 is:\n")
print(dotProduct)
Output
The output of the above program is:
arr1 is:
[[10 20]
[30 40]
[11 22]]
arr2 is:
[[22 33]
[11 12]]
Dot product of arr1 and arr2 is:
[[ 440 570]
[1100 1470]
[ 484 627]]
Code Explanation
- To use NumPy in the program, we imported numpy module.
- Defined two NumPy arrays arr1 and arr2, and then printed the original arrays on the screen.
- Then, we used the numpy.dot() method and passed arr1 and arr2 as an argument.
- Finally, printed the result on the screen, which will be the dot product of arr1 and arr2.
Python NumPy Programs »