DEV Community

Coding Panel
Coding Panel

Posted on • Originally published at codingpanel.com

Nxnxn matrix python3

A 3D matrix (NxNxN) in Python3 provides versatility in the representation of data. You can more easily express complex data structures with these three-dimensional arrays. These 3D matrices add an extra dimension, that is very useful when dealing with volumetric data. Three-dimensional arrays often referred to as NxNxN arrays are very useful in various fields and applications like computer vision, medical imaging, deep learning, augmented reality, and many more.

In the context of NxNxN matrix or 3D array:
– The first N represents the number of Rows in the matrix
– The second N represents the number of columns in the matrix
– The third N represents the number of layers or depth of the matrix

NxNxN Matrix

Implementing and working with three-dimensional arrays may sound tricky and difficult but nothing to worry about, Python3 is here to rescue you. Python3 has made it much simpler than you can think. In this blog, we will walk through a step-by-step approach to implementing and using 3D arrays using both possible approaches i.e.

NumPy
Lists
Implementing NxNxN Matrix using Python3
In this section, we will discuss both ways to implement and use NxNxN arrays using Python3.

Implementation using Lists

Implementing 3D array using nested lists and list comprehension is a basic or fundamental approach compared to using NumPy.

To implement a list-based approach for creating a 3D array in Python, you can think of it as creating a collection of lists. We will start with an empty list and append more lists to it to represent each layer of the 3D array. Within each layer of this 3D matrix, we will append lists to represent the rows, and inside each row, we will add the individual elements. This way, we will construct a hierarchy of lists, simulating the three dimensions of the matrix – layers, rows, and columns. By traversing through this hierarchy of lists, we can then access and edit various parts of that matrix.

Starting with the code, we have:

N = 3      #Defining size of NxNxN matrix 
Enter fullscreen mode Exit fullscreen mode

The next step is to create a 3D matrix filled with zeros

three_d_matrix = [[[0 for _ in range(N)] for _ in range(N)] for _ in range(N)]
Enter fullscreen mode Exit fullscreen mode

This line of code creates a 3D array (NxNxN matrix) filled with zeros using nested list comprehensions. Each for _ in range(N) loop creates a 1D list containing N zeros. Here, _ is a common convention used when we don’t need a loop variable.

Accessing Elements

To access and modify elements in 3D array, we do it by:

three_d_matrix[0][1][2] = 33       # Assigning the value 33 to the element at (0, 1, 2)

Enter fullscreen mode Exit fullscreen mode

To print the entire 3D array:


for layer in three_d_matrix:
    for row in layer:
        print(row)
    print("-" * 10)  # 10 dashes are used to seperate each layer
Enter fullscreen mode Exit fullscreen mode

The output for this print statement will be

[0,0,0]
[0,0,33]
[0,0,0]
----------
[0,0,0]
[0,0,0]
[0,0,0]
----------
[0,0,0]
[0,0,0]
[0,0,0]
----------
Enter fullscreen mode Exit fullscreen mode

Implementation using NumPy

NumPy is a Pyhton library used for numerical and scientific computation. It contains a wide range of built-in features that can be used for various things.

To use Numpy, the first and foremost thing is to import NumPy library.

import numpy as np
Enter fullscreen mode Exit fullscreen mode

Then we have,

N = 3  
# Create a 3D array filled with zeros
three_d_matrix = np.zeros((N, N, N), dtype=int)
Enter fullscreen mode Exit fullscreen mode

Here by np.zeros() we create a 3D array filled with zeros. The (N, N, N) argument specifies the shape of the array, and dtype=int specifies that the array should contain integer values.

Accessing Elements

To access and modify element

three_d_matrix[0, 1, 2] = 33
Enter fullscreen mode Exit fullscreen mode

Print Matrix

print(three_d_array)
Enter fullscreen mode Exit fullscreen mode

Output

[[[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]]]
Enter fullscreen mode Exit fullscreen mode

Iterating through NxNxN Matrices

To iterate through each element of a NxNxN matrix we to need to take help of a nested for loop.

import numpy as np
N = 3
array = np.random.rand(N, N, N)
# Iterate through the elements of the 3D array
for i in range(N):
    for j in range(N):
        for k in range(N):
            element = array[i, j, k]
            print(f"Element at ({i}, {j}, {k}) = {element}")
Enter fullscreen mode Exit fullscreen mode

Performing different operations on NumPy matrix
Addition
For bit wise addition of two NxNxN matrices

import numpy as np
N = 3
array1 = np.random.rand(N, N, N)
array2 = np.random.rand(N, N, N)
result = array1 + array2     # Element-wise addition
print(result)
Subtraction
Enter fullscreen mode Exit fullscreen mode

Similarly, for subtraction we have,

import numpy as np
N = 3
array1 = np.random.rand(N, N, N)
array2 = np.random.rand(N, N, N)
result = array1 - array2      # Element-wise subtraction
print(result)
Enter fullscreen mode Exit fullscreen mode

Multiplication

Multipying two 3D matrices populated with a random number using np.random.rand() function.

import numpy as np
N = 3 
# Create two 3D arrays (NxNxN arrays)
array1 = np.random.rand(N, N, N)  
array2 = np.random.rand(N, N, N)  
# Perform matrix multiplication
result = np.matmul(array1, array2)
print(result)
Enter fullscreen mode Exit fullscreen mode

We can also use np.zeros() and np.ones() or as desired to populate matix.
np.matmul() is a built-in NumPy function to multiply two matrices.

Transposition

import numpy as np
N = 3
array = np.random.rand(N, N, N)
transposed_array = array.transpose()  # Or array.T
print("Original Array:")
print(array)
print("\nTransposed Array:")
print(transposed_array)
Enter fullscreen mode Exit fullscreen mode

.transpose() to .T is a built-in NumPy function to perform transpose of a 3D array.

The transpose of a matrix is a new matrix in which the rows of the
original matrix become columns, and the columns become rows. In other
words, you interchange the rows and columns of the original matrix.

Comparison

Now, if we compare both approaches, For a number of reasons, using a list-based technique to implement and interact with NxNxN matrices in Python3 can be more difficult than using the NumPy approach. Nested lists can simulate multi-dimensional arrays, but since lists are by nature one-dimensional data structures, doing so can be difficult and error-prone, especially when working with higher dimensions. On the other hand, NumPy offers efficient storage, vectorized operations, and a variety of numerical computing tools and is specifically intended for multidimensional array operations.

It is the preferred option when working with NxNxN matrices and higher-dimensional arrays in Python3 because it makes code simpler, improves performance, and offers a more readable and natural approach to handling multi-dimensional data.

Conclusion

As we can clearly see through implementation code and comparison, Python3 has made usage and implementation of NxNxN matrix way simpler. We saw that numerical computations can be performed more quickly and with a broader variety of capabilities when using NumPy, which also offers greater efficiency. I hope you find this tutorial helpful. Thanks for reading.

Top comments (0)