w3resource

Advanced NumPy Exercises - Dot product of two arrays of different dimensions

NumPy: Advanced Exercise-1 with Solution

Write a NumPy program to find the dot product of two arrays of different dimensions.

Sample Solution:

Python Code:

import numpy as np
# Define the two arrays
nums1 = np.array([[1, 2], [3, 4], [5, 6]])
nums2 = np.array([7, 8])
print("Original arrays:")
print(nums1)
print(nums2)
# Find the dot product
result = np.dot(nums1, nums2)
# Print the result
print("Dot product of the said two arrays:")
print(result)

Sample Output:

Original arrays:
[[1 2]
 [3 4]
 [5 6]]
[7 8]
Dot product of the said two arrays:
[23 53 83]

Explanation:

In the above exercise -

nums1 = np.array([[1, 2], [3, 4], [5, 6]]): This code creates a 2D NumPy array with shape (3, 2) containing the values [[1, 2], [3, 4], [5, 6]] and assigns it to the variable nums1.

nums2 = np.array([7, 8]): This code creates a 1D NumPy array with shape (2,) containing the values [7, 8] and assigns it to the variable nums2.

result = np.dot(nums1, nums2): Here dot() function performs dot product between nums1 and nums2, and assigns the result to the variable result. Since nums1 has shape (3, 2) and nums2 has shape (2,), the dot product results in a 1D array with shape (3,) containing the values [23, 53, 83].

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: NumPy Advanced Exercises Home.
Next: Stack a 3x3 identity matrix vertically and horizontally.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.