Open In App

NumPy – 3D matrix multiplication

Improve
Improve
Like Article
Like
Save
Share
Report

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python.

What is 3D Matrix Multiplication?

A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors.

Here we will see two different examples of matrix multiplication where we have used different dimensions in each example.

Multiplication of matrix A of shape (3,3,2) with 3D matrix B of shape (3,2,4)

The first matrix is a stack of three 2D matrices each of shape (3,2), and the second matrix is a stack of 3 2D matrices, each of shape (2,4). The matrix multiplication between these two will involve three multiplications between corresponding 2D matrices of A and B having shapes (3,2) and (2,4) respectively. Specifically, the first multiplication will be between A[0] and B[0], the second multiplication will be between A[1] and B[1], and finally, the third multiplication will be between A[2] and B[2]. The result of each individual multiplication of 2D matrices will be of shape (3,4). Hence, the final product of the two 3D matrices will be a matrix of shape (3,3,4).

Python3




import numpy as np
np.random.seed(42)
A = np.random.randint(0, 10, size=(3, 3, 2))
B = np.random.randint(0, 10, size=(3, 2, 4))
print("A:\n{}, shape={}\nB:\n{}, shape={}".format(
  A, A.shape, B, B.shape))
C = np.matmul(A, B)
print("Product C:\n{}, shape={}".format(C, C.shape))


Output:

Multiplication of matrix A of shape (3,5,2) with 3D matrix B of shape (3,2,5)

The code generates two random integer matrices A and B, then multiplies them using matrix multiplication. It prints the shapes and content of these matrices. Matrix multiplication is a fundamental operation in linear algebra and the code demonstrates how to perform it using NumPy in Python.

Python3




import numpy as np
np.random.seed(42)
A = np.random.randint(0, 10, size=(3, 5, 2))
B = np.random.randint(0, 10, size=(3, 2, 5))
print("A:\n{}, shape={}\nB:\n{}, shape={}".format(
  A, A.shape, B, B.shape))
C = np.matmul(A, B)
 
print("Product C:\n{}, shape={}".format(C, C.shape))


Output:

Screenshot-2023-10-18-at-40133-PM



Last Updated : 02 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads