w3resource

NumPy: Generate a matrix product of two arrays

NumPy Mathematics: Exercise-15 with Solution

Write a NumPy program to generate a matrix product of two arrays.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating two matrices x and y
x = [[1, 0], [1, 1]]
y = [[3, 1], [2, 2]]

# Displaying matrices x and y
print("Matrices and vectors.")
print("x:")
print(x)
print("y:")
print(y)

# Computing the matrix product of matrices x and y using np.matmul()
print("Matrix product of above two arrays:")
print(np.matmul(x, y)) 

Sample Output:

Matrices and vectors.                                                  
x:                                                                     
[[1, 0], [1, 1]]                                                       
y:                                                                     
[[3, 1], [2, 2]]                                                       
Matrix product of above two arrays:                                    
[[3 1]                                                                 
 [5 3]] 

Explanation:

In the above code, there are two matrices x and y that we want to multiply using matrix multiplication. The np.matmul() function performs the matrix multiplication of these two matrices.

Matrix multiplication is only defined if the number of columns of the first matrix matches the number of rows of the second matrix. In this case, the matrices x and y have the same shape (2x2), so matrix multiplication is valid.

The result of the matrix multiplication is a new matrix whose dimensions are determined by the number of rows of the first matrix and the number of columns of the second matrix. In this case, since x has 2 rows and y has 2 columns, the resulting matrix will be of shape (2, 2).

Pictorial Presentation:

NumPy Mathematics: Create an inner product of two arrays.

Python-Numpy Code Editor:

Previous: Write a NumPy program to generate inner, outer, and cross products of matrices and vectors.
Next: Write a NumPy program to find the roots of the following polynomials.

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.