What is the numpy.matmul() function from NumPy in Python?
Overview
The matmul() function in Python returns the matrix product of two arrays.
Syntax
numpy.matmul(x1, x2, out = None)
Parameter value
The matmul() function takes the following parameter values:
x1, x2: This represents the input arrays. Scalars are not allowed.out: This represents a location at which the result is stored. This parameter is optional.
Return value
The multiply() function returns the matrix product of x1 and x2.
Code example
import numpy as np# creating `2D` arraysx1 = np.array([[1, 2], [1, 2]])x2 = np.array([[2, 1], [1, 4]])# calling the matmul() functionmyarray1 = np.matmul(x1, x2)print("This is myarray1",myarray1)# creating a 2D and a 1D arraysx3 = np.array([[1, 2], [1, 2]])x4 = np.array([1, 3])# calling the matmul() functionmyarray2 = np.matmul(x3, x4)print("This is myarray2", myarray2)
Code explanation
- Line 1: We import the
numpyfunction. - Lines 3–4: We use the
array()function to create two2Darrays,x1andx2, of the same dimension. - Line 8: We implement the
matmul()function on the arraysx1andx2. We assign the result to a variable calledmyarray1. - Line 9: We print the variable
myarray1. - Lines 13–14: We use the
array()function to create2Dand1Darrays and name themx3andx4, respectively. - Line 17: We implement the
matmul()function on the arraysx3andx4. We assign the result to another variable calledmyarray2. - Line 18: We print the variable
myarray2.