NumPy: Multiply a 5x3 matrix by a 3x2 matrix and create a real matrix product
Write a NumPy program to multiply a 5x3 matrix by a 3x2 matrix and create a real matrix product.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Generating a random array of shape (5, 3)
x = np.random.random((5,3))
# Displaying the first array
print("First array:")
print(x)
# Generating another random array of shape (3, 2)
y = np.random.random((3,2))
# Displaying the second array
print("Second array:")
print(y)
# Computing the dot product of the two arrays
z = np.dot(x, y)
# Displaying the dot product of the arrays
print("Dot product of two arrays:")
print(z)
Sample Output:
First array: [[ 0.44349753 0.81043761 0.00771825] [ 0.64004088 0.86774612 0.19944667] [ 0.61520091 0.24796788 0.93798297] [ 0.22156999 0.61318856 0.82348994] [ 0.91324026 0.13411297 0.00622696]] Second array: [[ 0.73873542 0.06448186] [ 0.90974982 0.06409165] [ 0.22321268 0.39147412]] Dot product of two arrays: [[ 1.06664562 0.08356133] [ 1.30677176 0.17496452] [ 0.88942914 0.42275803] [ 0.90534318 0.37596252] [ 0.79804212 0.06992065]]
Explanation:
In the above code –
The np.random.random() function creates an array of random numbers between 0 and 1 of the specified shape. In this case, x is a 5x3 array and y is a 3x2 array.
The np.dot() function takes two arrays and returns their dot product, which is the matrix multiplication of the two arrays. In this case, since the first array x has shape (5,3) and the second array y has shape (3,2), their dot product will have shape (5,2).
z = np.dot(x, y) - The resulting matrix z is the product of x and y and is a 5x2 array. The value in row i and column j of z is the dot product of row i of x and column j of y.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics