NxNxN Matrix in Python 3: Exploring NumPy’s 3D Array Read it later

4/5 - (4 votes)

Matrix is the fundamental mathematical structure used in various fields like computer science, physics, and engineering. While you may be familiar with two-dimensional matrices, have you heard of the NxNxN matrix? It adds a third dimension, resulting in a cube-like structure. In this blog, we’ll explore the NxNxN matrix in Python 3 Using NumPy, covering the creation, manipulation, visualization, advanced operations, and real-world applications. Join us as we explore the mysteries of NxNxN matrices in Python 3. Let’s begin!

What is the NxNxN Matrix?

An NxNxN matrix, also known as NxNxN cube or NxNxN puzzle, is a three-dimensional (3D) matrix, that expands upon the concept of a traditional matrix by introducing an extra dimension.

It can be visualized as a stack of two-dimensional matrices arranged in a three-dimensional space. Each element within the matrix is uniquely identified by three indices: row (i), column (j), and depth (k).

NxNxN Matrix Illustration

Creating NxNxN Matrix in Python 3

Alright, now that we have a good understanding of what an NxNxN matrix is, let’s dive into how we can create one using Python 3. Creating an NxNxN matrix in Python can be done using various approaches, each with its own advantages. Let’s explore a few popular methods:

Using Range Function

The traditional approach involves initializing a 3D matrix using nested loops. We can use the range() function to iterate over the desired dimensions and assign values to each element of the matrix.

n = 3  # Set the desired dimension
matrix = []
for i in range(n):
    rows = []
    for j in range(n):
        cols = []
        for k in range(n):
            cols.append(0)  # Set the initial value of each element

💡Did you know? The range() function is a generator in Python.

Using List Comprehension

List comprehension provides a more concise and elegant way of creating an NxNxN matrix. With list comprehension, we can initialize the matrix and assign values in a single line of code. Here’s an example:

N = 3

matrix = [[[0 for k in range(N)] for j in range(N)] for i in range(N)]

In this example, we use a nested list comprehension to create a 3x3x3 matrix filled with zeros. The innermost comprehension sets the values for the third dimension, followed by the second and first dimensions.

Using Lambda Function

Another interesting approach is to use lambda functions in conjunction with the map() function. This allows us to create a matrix and assign values based on a specified function. Here’s an example:

N = 3

matrix = list(map(lambda i: list(map(lambda j: list(map(lambda k: 0, range(N))), range(N))), range(N)))

While this method may not be as intuitive as the previous ones, it provides flexibility for more complex operations on the matrix.

Using NumPy

When it comes to working with matrices, especially for large-scale computations, the best approach is to utilize the powerful NumPy library. NumPy offers efficient and optimized functions for matrix operations, making it the go-to choice for working with matrices in Python. Creating an NxNxN matrix with NumPy is straightforward:

import numpy as np
N = 3
matrix = np.zeros((N, N, N))

In this example, we use the np.zeros() function to create an NxNxN matrix filled with zeros. NumPy provides a wide range of functions to manipulate and operate on matrices efficiently.


array([[[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]]])

📝 Note: Out of the methods mentioned, using NumPy is highly recommended due to its efficiency and extensive functionality. It not only simplifies matrix creation but also offers fast computation and a plethora of functions for advanced matrix operations.

Creating a Matrix with Random Values

We can use the NumPy library to create a matrix with random values. With NumPy’s random module, we have access to functions that generate random numbers. One such function is numpy.random.randint, which generates random integer values within a specified range.

Here’s an example of creating a 3x3x3 matrix with random values:

import numpy as np

matrix = np.random.randint(0, 100, size=(4, 4, 4))

In the above example, we import NumPy and use np.random.randint to generate the matrix. Each matrix element will be an independent random value between 0 and 99.


array([[[ 2, 75, 75],
        [89, 55, 77],
        [66, 56, 99]],

       [[75, 94, 71],
        [57, 44, 23],
        [76, 35, 60]],

       [[63, 74, 33],
        [44, 39,  3],
        [88, 27, 25]]])

Convert the Python list to NumPy

In order to convert a Python list into a NumPy array we can make use of the amazing NumPy library. Using the np.array() function, we can effortlessly transform a list into a NumPy array.


import numpy as np

arr = [[[0,1,2], [0,1,2], [0,1,2]], [[0,1,2], [0,1,2], [0,1,2]], [[0,1,2], [0,1,2], [0,1,2]]]
arr2 = np.array(arr)

In the above example, we apply the np.array() function to my_list, we obtain a NumPy array stored in the variable my_array.


array([[[0, 1, 2],
        [0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2],
        [0, 1, 2]]])

Reshaping the Matrix

Reshaping a matrix in Python allows us to change its dimensions while keeping the original data intact. With NumPy, we can easily reshape matrices using the reshape() function.

For instance, let’s say we have a 3x3x3 matrix and want to reshape it into a 9×3 matrix. We can achieve this by using the reshape() function:

import numpy as np

matrix = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
                   [[10, 11, 12], [13, 14, 15], [16, 17, 18]],
                   [[19, 20, 21], [22, 23, 24], [25, 26, 27]]])

reshaped_matrix = np.reshape(matrix, (9, 3))

In this example, we import NumPy, create a 3x3x3 matrix, and then reshape it into a 9×3 matrix using reshape(). The resulting reshaped_matrix maintains the original values of the elements but has a different structure.


array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12],
       [13, 14, 15],
       [16, 17, 18],
       [19, 20, 21],
       [22, 23, 24],
       [25, 26, 27]])

📝 Note: The total number of elements in the original matrix must match the total number of elements in the reshaped matrix. Otherwise, a ValueError will be raised.

Enumerate NumPy Array

To enumerate an NxNxN matrix in Python, we can leverage the power of the NumPy library. Using the ndenumerate() function from NumPy, we can iterate over each element of the matrix, accessing both its value and corresponding indices.

💡Are you missing the conceptual knowledge about Python enumerate function, learn now!

Here’s an example:

import numpy as np

# Create a matrix
matrix = np.zeros((3, 3, 3))

# Enumerate the elements
for indices, value in np.ndenumerate(matrix):
    i, j, k = indices
    # Perform operations or access values using i, j, and k
    # Example: Assign a new value to the element
    matrix[i, j, k] = i + j + k


array([[[0., 1., 2.],
        [1., 2., 3.],
        [2., 3., 4.]],

       [[1., 2., 3.],
        [2., 3., 4.],
        [3., 4., 5.]],

       [[2., 3., 4.],
        [3., 4., 5.],
        [4., 5., 6.]]])

By utilizing ndenumerate(), we can efficiently traverse the elements of an NxNxN matrix, gaining control over individual elements and their corresponding indices. This enumeration process empowers us to perform targeted operations and extract valuable information from the matrix.

Basic Operations on NxNxN Matrix in Python 3

Now that we have a good understanding of NxNxN matrices and how to create them in Python, let’s explore some basic operations that we can perform on these matrices. These operations include addition, subtraction, and multiplication. To make our lives easier, we will utilize the powerful NumPy library, which provides efficient functions for matrix operations.

Addition and Subtraction

Performing addition and subtraction on NxNxN matrices follows a straightforward element-wise approach. In other words, we simply add or subtract corresponding elements of the matrices to obtain the result.

Let’s consider two 3x3x3 matrices, matrix1 and matrix2, and perform addition and subtraction using NumPy:

# Addition
result_addition = np.add(matrix1, matrix2)

# Subtraction
result_subtraction = np.subtract(matrix1, matrix2)

In this example, we create two matrices, matrix1, and matrix2, filled with values. Then, using the np.add() and np.subtract() functions, we perform element-wise addition and subtraction, respectively. The resulting matrices, result_addition, and result_subtraction, will contain the summed and subtracted values, respectively.

Matrix Multiplication

Matrix multiplication for NxNxN matrices is slightly more complex than addition and subtraction. NumPy provides two functions for matrix multiplication: matmul and multiply.

NumPy matmul Function

The matmul function in NumPy performs matrix multiplication by multiplying the corresponding elements and summing them up to produce the resulting matrix. The dimensions of the matrices involved in the multiplication must be compatible.

# Matrix multiplication using matmul
result_matmul = np.matmul(matrix1, matrix2)

In this example, we use the matmul function to multiply matrix1 and matrix2, resulting in the matrix result_matmul.

NumPy multiply Function

The multiply function in NumPy, on the other hand, performs element-wise multiplication between two matrices of the same shape, without summing them up. This means that the resulting matrix will have the same shape as the input matrices.

# Element-wise multiplication using multiply
result_multiply = np.multiply(matrix1, matrix2)

Here, we use the multiply function to perform element-wise multiplication between matrix1 and matrix2, resulting in the matrix result_multiply.

NxNxN Matrix Slicing in Python 3

Matrix slicing is a powerful technique that allows us to extract specific portions or subsets of a matrix. In the context of NxNxN matrices, slicing becomes even more interesting as we have an additional dimension to work with. By slicing an NxNxN matrix, we can retrieve subsets of elements that meet certain criteria or patterns.

Slicing Syntax:

sliced_matrix = matrix[start_i:end_i, start_j:end_j, start_k:end_k]

Let’s explore matrix slicing in NxNxN matrices using Python 3. Consider the following 3x3x3 matrix as an example:

matrix = [[[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]],
          [[10, 11, 12],
           [13, 14, 15],
           [16, 17, 18]],
          [[19, 20, 21],
           [22, 23, 24],
           [25, 26, 27]]]

To slice this matrix, we can use indexing along each dimension. Here are some slicing techniques:

1. Slicing Rows

We can extract specific rows by specifying the desired range of indices along the first dimension. For example, to slice the second row (index 1) of the matrix, we can use the following code:

row = matrix[1, :, :]

The resulting slice will be [[10, 11, 12], [13, 14, 15], [16, 17, 18]].

2. Slicing Columns

Similarly, we can slice columns by specifying the desired range of indices along the second dimension. To slice the third column (index 2) of the matrix, we can use the following code:

column = matrix[:, 2, :]

The resulting slice will be [[3], [6], [9]].

3. Slicing Depths

To slice elements along the third dimension, we specify the range of indices along the third dimension. For example, to slice the first depth (index 0), we can use the following code:

depth = matrix[:, :, 0]

The resulting slice will be [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

4. Combining Slicing Techniques

We can combine slicing techniques to extract more specific subsets of the matrix. For instance, to slice a portion of the matrix that includes the second column (index 1) and the first two depths (indices 0 and 1), we can use the following code:

subset = matrix[:, 1, :2]

The resulting slice will be [[2], [5], [8], [11], [14], [17]].

Transposing NxNxN Matrix in Python 3

To transpose an NxNxN matrix using NumPy, we can use the numpy.transpose() function. This function takes the matrix as input and returns the transposed matrix as output. It swaps the rows with the columns, transforming the original matrix into a new one.

Code for transposing the matrix:

transposed_matrix = np.transpose(matrix)

By transposing the matrix, the rows become columns and the columns become rows. The np.transpose() function simplifies this process, making it easy to work with NxNxN matrices.

Rotation of 3D NxNxN Matrix with NumPy

Rotating a 3D matrix might seem complex, but with NumPy, it becomes surprisingly straightforward. We can achieve this using the rot90 function, a very handy function that performs rotations in multiples of 90 degrees.

Let’s explore this concept with a simple example:

import numpy as np
from pprint import pprint

# Creating a random 3D matrix
arr1 = np.random.randint(1, 10, size=(2, 3, 2))
print("Original Matrix:\n")

# Rotating the matrix by 90 degrees
rot = np.rot90(arr1, 1)
print("\nMatrix after Rotation:\n")

In this code, we import the necessary libraries and create a random 3D matrix. By applying the np.rot90 function, we rotate the matrix by 90 degrees (1 * 90 degrees). The resulting rotated matrix is printed to the console.


Original Matrix:

array([[[1, 7],
        [5, 9],
        [6, 1]],
       [[6, 1],
        [3, 7],
        [7, 6]

Matrix after Rotation:

[[[6 1]
  [7 6]]
 [[5 9]
  [3 7]]
 [[1 7]
  [6 1]]]

Applications of NxNxN Matrix

NxNxN matrices have practical applications across different fields, showcasing their versatility. Let’s explore some key areas where these matrices find use.

  1. Image Processing and Computer Graphics: In image processing, the NxNxN matrix helps improve images by applying filters for effects like blurring or edge detection. They also enable realistic 3D modeling and transformations in computer graphics.
  2. Data Analysis and Machine Learning: NxNxN matrix handles complex data in fields like data analysis and machine learning. They efficiently store and process multi-dimensional datasets, facilitating tasks such as image recognition and natural language processing.
  3. Quantum Computing: The NxNxN matrix plays a crucial role in quantum computing, representing quantum states and enabling calculations in quantum algorithms. They contribute to advancements in cryptography and optimization.
  4. Physical Simulations and Engineering: In physical simulations and engineering, NxNxN matrix models and analyzes complex systems like fluid dynamics or structural analysis. They help predict real-world phenomena accurately.
  5. Cryptography and Network Security: The NxNxN matrix is used for encryption, decryption, and key generation in cryptography. They provide a secure framework for transmitting sensitive information and enhance network security.

Wrapping Up

In conclusion, we have explored NxNxN matrices in Python, from their basic creation and operations to advanced topics and practical applications. These three-dimensional matrices serve as powerful tools in various domains, such as image processing, data analysis, and 3D modeling. By using libraries like NumPy and embracing parallel processing techniques, we can unlock their full potential.

Keep exploring and applying these concepts to expand your skills and solve complex problems effectively. Happy coding!

Frequently Asked Questions (FAQs)

What is an NxNxN matrix?

An NxNxN matrix, also known as NxNxN cube or NxNxN puzzle, is a three-dimensional (3D) matrix, that expands upon the concept of a traditional matrix by introducing an extra dimension.

How do I create an NxNxN matrix in Python?

Traditionally, creating an NxNxN matrix in Python is achieved using nested lists by defining the desired dimensions and using list comprehension. But in the modern world, you can also use the NumPy library to create an N-dimensional matrix.

Is there any library for working with the NxNxN matrix in Python?

Yes, Python offers libraries like NumPy that provide extensive functionality for working with matrices, including NxNxN matrices. NumPy offers optimized functions for matrix operations, making computations faster and more efficient.


Was This Article Helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *