Free cookie consent management tool by TermsFeed The matmul() function of numpy | Pythontic.com

The matmul() function of numpy

Overview:

  • The matmul() function of NumPy module multiplies two n-dimensional matrices and returns the product of the two matrices. 

Example 1 - Muliplication of two 2-dimensional matrices using matmul():

# Example Python program that multiplies two-dimensional matrices using
# the numpy functoin matmul()
import numpy
import random

# Create ndarrays of numbers
n1 = numpy.ndarray(shape = (3, 3), 
                   dtype = numpy.int32)

n2 = numpy.ndarray(shape = (3, 3), 
                   dtype = numpy.int32)

# Populate the numbers
for i in range (0, 3):
    for j in range (0, 3):
        n1[i][j] = random.randrange(2, 20)
        n2[i][j] = random.randrange(2, 10)

# Matrix multiplication of two-dimensional numpy
# arrays
result = numpy.matmul(n1, n2)
print(result)

Output:

[[210 128 138]

 [244 173 237]

 [314 208 258]]

Example 2: Multiplying an 3-dimensional matrix with a 2-dimensional matrix

# Example Python program that uses matmul() function of 
# NumPy to multiply two matrices - one a 3-dimensional matrix and
# another a 2-dimensional matrix

import numpy

# Create a 3-dimensional matrix
n1 = numpy.arange(0, 54, 2)
a1 = n1.reshape(3, 3, 3)
print("A 3-dimensional matrix:")
print(a1)

# Create a 2-dimensional matrix
n2 = numpy.arange(9)
a2 = n2.reshape(3, 3)
print("A 2-dimensional matrix:")
print(a2)

# Multiply the two matrices
result = numpy.matmul(a1, a2)
print("Result of multiplying a 3-dimensional matrix with a 2-dimensional matrix:")
print(result)

Output:

A 3-dimensional matrix:

[[[ 0  2  4]

  [ 6  8 10]

  [12 14 16]]

 

 [[18 20 22]

  [24 26 28]

  [30 32 34]]

 

 [[36 38 40]

  [42 44 46]

  [48 50 52]]]

A 2-dimensional matrix:

[[0 1 2]

 [3 4 5]

 [6 7 8]]

Result of multiplying a 3-dimensional matrix with a 2-dimensional matrix:

[[[ 30  36  42]

  [ 84 108 132]

  [138 180 222]]

 

 [[192 252 312]

  [246 324 402]

  [300 396 492]]

 

 [[354 468 582]

  [408 540 672]

  [462 612 762]]]

 


Copyright 2025 © pythontic.com