Facebook Page Twitter Page LinkedIn Page
× NumPy Tutorial NumPy Resources


The NumPy matmul() function is used to perform matrix product of two arrays. Specifically,

  • If both a and b are 2-D arrays, it is matrix multiplication.
  • If a or b is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed.
  • If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.

Please note that multiplication by scalars is not allowed by this function.

Syntax

numpy.matmul(a, b, out=None)

Parameters

a Required. Specify first array-like argument. scalars not allowed.
b Required. Specify second array-like argument. scalars not allowed.
out Optional. Specify output array for the result. The default is None. If provided, it must have the same shape as output.

Return Value

Returns the matrix product of the two arrays.

Exception

Raises ValueError exception, if the last dimension of a is not the same size as the second-to-last dimension of b or a scalar value is passed in.

Example: matmul() function with 1-D arrays

When two 1-D arrays are used, the function returns inner product of the arrays.

import numpy as np
Arr1 = [5, 8]
Arr2 = [10, 20]

#returns 5*10 + 8*20 = 210
print(np.matmul(Arr1, Arr2))

The output of the above code will be:

210

Example: matmul() function with matrix

When two matrix are used, the function returns matrix multiplication.

import numpy as np
Arr1 = np.array([[1, 2], 
                 [3, 4]])
Arr2 = np.array([[10, 20], 
                 [30, 40]])
Arr3 = np.matmul(Arr1, Arr2)

print(Arr3)

The output of the above code will be:

[[ 70 100]
 [150 220]]

The matrix multiplication is calculated as:

[[1*10+2*30 1*20+2*40]
 [3*10+4*30 3*20+4*40]]

= [[ 70 100]
   [150 220]]

❮ NumPy - Functions