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` arrays
x1 = np.array([[1, 2], [1, 2]])
x2 = np.array([[2, 1], [1, 4]])
# calling the matmul() function
myarray1 = np.matmul(x1, x2)
print("This is myarray1",myarray1)
# creating a 2D and a 1D arrays
x3 = np.array([[1, 2], [1, 2]])
x4 = np.array([1, 3])
# calling the matmul() function
myarray2 = np.matmul(x3, x4)
print("This is myarray2", myarray2)

Code explanation

  • Line 1: We import the numpy function.
  • Lines 3–4: We use the array() function to create two 2D arrays, x1 and x2, of the same dimension.
  • Line 8: We implement the matmul() function on the arrays x1 and x2. We assign the result to a variable called myarray1.
  • Line 9: We print the variable myarray1.
  • Lines 13–14: We use the array() function to create 2D and 1D arrays and name them x3 and x4, respectively.
  • Line 17: We implement the matmul() function on the arrays x3 and x4. We assign the result to another variable called myarray2.
  • Line 18: We print the variable myarray2.

Free Resources