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.
To find the dot product of two arrays with different dimensions using NumPy, you can leverage the numpy.dot function. The dot product calculation depends on the dimensionality of the arrays. If one array is 1-D and the other is 2-D, the dot product is performed as a matrix-vector multiplication. If both arrays are 2-D, it results in matrix multiplication. This flexibility allows for efficient linear algebra computations with arrays of varying shapes.
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)
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/advanced-numpy-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics