NumPy matmul()

The matmul() method is used to perform matrix multiplication in NumPy.

import numpy as np

# create two matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])

# perform matrix multiplication using matmul() result = np.matmul(matrix1, matrix2)
print(result) ''' Output: [[19 22] [43 50]] '''

matmul() Syntax

The syntax of matmul() is:

numpy.matmul(first_matrix, second_matrix, out=None)

matmul() Arguments

The matmul() method takes the following arguments:

  • first_matrix - represents the first matrix that we want to multiply
  • second_matrix - represents the second matrix that we want to multiply
  • out (optional) - allows us to specify a matrix where the result will be stored

matmul() Return Value

The matmul() method returns the matrix product of the input arrays.


Example 1: Multiply Two Matrices

import numpy as np

# create two matrices
matrix1 = np.array([[1, 3], [5, 7]])       
matrix2 = np.array([[2, 6], [4, 8]])

# calculate the dot product of the two matrices
result = np.matmul(matrix1, matrix2)

print("matrix1 x matrix2: \n", result)

Output

matrix1 x matrix2: 
 [[14 30]
 [38 86]]

Note: We can only multiply two matrices when they have a common dimension size. For example, For A = (M x N) and B = (N x K) when we multiply, C = A * B the resulting matrix is of size C = (M x K).


Example 2: Use of out Argument in matmul()

import numpy as np

# create two matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])

# create an output array
result = np.zeros((2, 2), dtype=int)

# perform matrix multiplication using matmul() and store the output in the result array
np.matmul(matrix1, matrix2, out=result)

print(result)

Output

[[19 22]
 [43 50]]

In this example, we created an output array called result using np.zeros() with the desired shape (2, 2) and data type int.

We then passed this result array as the out parameter in np.matmul().

The matrix multiplication is computed and stored in the result array.