How to do Matrix product of NumPy arrays | np.matmul

In this post, we are going to learn How to do Matrix product of NumPy arrays. We are going to learn this with the help of many examples and we will see code examples as well. By the end of this post, you will be able to answer the below questions.

NumPy matmul() function


In Numpy, we have matmul() function that is used to do the Matrix product of two arrays. With this function, we can’t use scalar values for our input.

  • If we pass a 1-d array as argument ,the function converts it into a matrix by appending a 1 to its dimension. This is removed after the multiplication is done.
  • If we pass a 2-d array or higher, the function treats it as a stack of matrices in the last two indexes.
    The matmul() method is very helpful to handle the cases when we dont know what are the size of the arrays
    that we are going to use for computation.

The syntax of this function is:

numpy.matmul(x1, x2, /, out=None, *, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj, axes, axis]) = <ufunc 'matmul'>

Parameters:

ParametersParameter Mandatory or NotDetails
x1MandatoryFirst Input arrays to be multiplied. It should not be a scaler number
x2 Mandatory Second, Input arrays are to be multiplied. It should not be a scaler number
OutNot-Mandatoryout: [ndarray, optional] A location into which the result is stored. If
provided, it must have a shape that matches the signature (n,k),(k,m)->(n,m).If not provided or None, a freshly-allocated array is returned.

Return:

[ndarray] The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.

Raises ValueError

  • If the last dimension of x1 is not the same size as the second-to-last dimension of x2.
  • If a scalar value is passed in.
  • The behavior depends on the arguments in the following way.
  • If both arguments are 2-D they are multiplied like conventional matrices.
  • 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.
  • If the first argument 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 the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed.

1. NumPy matmul() to product 2 Scaler numbers


In this example, We are going to discuss How to multiply matrices in numpy by using matmul() function to multiply a scaler number with another scaler number. As per the documentation of matmul(), this will not work. You can see below the code example we are getting an error. Scaler multiplications are not allowed using matmul() function.

import numpy as np
num1 = 5
num2 = 4
product = np.matmul(num1, num2)
print ("Multiplication Result is : ", product)

Output :

Traceback (most recent call last):
File "C:/Users/Contract/Desktop/Programs/NumpyTest.py", line 5, in
product = np.matmul(num1, num2)
ValueError: matmul: Input operand 0 does not have enough dimensions (has 0, gufunc core with signature (n?,k),(k,m?)->(n?,m?) requires 1)

2. NumPy matmul() with Scaler numbers and 1D array


In this example, we are trying to use matmul() function to multiply a scaler number with a linear array. As per the documentation of matmul() this will not work. You can see below the code example we are getting an error. Scaler multiplications are not allowed using matmul() function.

import numpy as np
num1 = 5
arr1 = np.array([1, 2, 3] )
product = np.matmul(num1, arr1)
print ("Multiplication Result is : ", product)

Output

Traceback (most recent call last):
File "C:/Users/Contract/Desktop/Programs/NumpyTest.py", line 5, in
product = np.matmul(num1, arr1)
ValueError: matmul: Input operand 0 does not have enough dimensions (has 0, gufunc core with signature (n?,k),(k,m?)->(n?,m?) requires 1)

3. NumPy matmul() on two linear array


In this example, we are going to learn how to use the matmul() function on two 1D arrays in numpy.

It is working like (1×5) + (2×4) + (3×3) + (4×2) + (5×1) = 35

import numpy as np
arr1 = np.array([1, 2, 3, 4, 5] )
arr2 = np.array([5, 4, 3, 2, 1]) 
print ("1st Input array : ", arr1)
print ("2nd Input array : ", arr2)
product = np.matmul(arr1, arr2)
print ("Matrix product Result of Linear arrays is : ", product)

Output

1st Input array : [1 2 3 4 5]
2nd Input array : [5 4 3 2 1]
Matrix product Result of Linear arrays is : 35

4.matmul() on two Multiply multi-dimensional Numpy Array


In this example, we are going learn how to using matmul() on two Multiply multi-dimensional arrays in numpy.
But the sizes are not suitable for the matrix products so we will get a value error.

import numpy as np
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([[6, 5, 4], [3, 2, 1]])
print ("1st Input array : ", arr1)
print ("2nd Input array : ", arr2)
product = np.matmul(arr1, arr2)
print ("Matrix product Result of 2D arrays is : ", product)

Output

1st Input array : [[1 2 3]
[4 5 6]]
2nd Input array : [[6 5 4]
[3 2 1]]
Traceback (most recent call last):
File "C:/Users/Contract/Desktop/Programs/NumpyTest.py", line 8, in
product = np.matmul(arr1, arr2)
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)

To resolve this error, we need to make sure the sizes of the arrays are a x N and N x b.Here is an good example:

import numpy as np
arr1 = np.array([[1, 2, 3], [4, 5, 6],[7, 8, 9]])
arr2 = np.array([[9, 8, 7],[6, 5, 4], [3, 2, 1]])
print ("1st Input array : ", arr1)
print ("2nd Input array : ", arr2)
product = np.matmul(arr1, arr2)
print ("Matrix product Result of 2D arrays is : ", product)

Output:

1st Input array : [[1 2 3]
[4 5 6]
[7 8 9]]
2nd Input array : [[9 8 7]
[6 5 4]
[3 2 1]]
Matrix product Result of 2D arrays is : [[ 30 24 18]
[ 84 69 54]
[138 114 90]

An explanation of this matrix product is: 0th row of array 1 [1 2 3] and 0th column of array 2

[9 6 3 ]

will make the first element of the resultant array.

(1×9) + (2×6) + (3×3) = 30

Similarly, row 0 and column 1 will give you the next element.
(1×8) + (2×5) + (3×2) = 24