# Adding custom dimension in Matrix using Python

Matrices are fundamental data structures in linear algebra and are extensively used in various scientific and mathematical computations. A matrix is a rectangular array of numbers arranged in rows and columns. It is commonly represented as a two-dimensional grid. However, there are scenarios where we may need to manipulate matrices with additional dimensions, either for data transformation or to perform advanced mathematical operations.

Python, being a versatile programming language, offers a rich ecosystem of libraries that provide powerful tools for matrix operations. One such library is NumPy, which stands for Numerical Python. NumPy provides efficient and convenient tools for working with arrays, including matrices, along with a wide range of mathematical functions.

Before we proceed with the implementation, let's ensure that NumPy is installed on your machine. If you don't have it installed, you can easily install it using pip, the Python package installer, by running the following command −

pip install numpy


Once NumPy is installed, we can proceed with creating and modifying matrices.

Next, we'll use the numpy.array function to create our matrix. Here's an example −

matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])


The array function accepts a nested list as an argument, where each list represents a row in the matrix. In our example, we have a 3x3 matrix.

To add a custom dimension to a matrix, we can use the numpy.newaxis attribute. The newaxis attribute allows us to increase the dimensionality of an existing matrix by one. Let's see how it works

new_matrix = matrix[:, np.newaxis]


In the code above, [:, np.newaxis] adds a new dimension to our matrix by inserting a new axis at the second position. The colon : represents all rows, and np.newaxis indicates the position where the new axis should be inserted. This operation effectively transforms the original 2-dimensional matrix into a 3-dimensional matrix.

### Example

Let's print the original matrix and the new matrix to observe the changes −

print("Original Matrix:")
print(matrix)

print("\nNew Matrix:")
print(new_matrix)


### Output

Running the code will produce the following output

Original Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]

New Matrix:
[[[1 2 3]]
[[4 5 6]]
[[7 8 9]]]


As you can see, the new matrix has an additional dimension compared to the original matrix. Each row of the original matrix is now encapsulated within its own inner array. This effectively increases the dimensionality of the matrix. Adding a custom dimension can be useful in scenarios where you need to perform operations that require higher-dimensional matrices, such as advanced machine learning algorithms or tensor computations.

One important concept to understand when adding a custom dimension to a matrix in NumPy is broadcasting. Broadcasting is a powerful mechanism in NumPy that allows arrays of different shapes to be operated on together. When adding a custom dimension to a matrix, broadcasting can automatically adjust the shapes of the arrays involved in computations.

Let's consider an example to demonstrate broadcasting −

matrix1 = np.array([[1, 2, 3],
[4, 5, 6]])

matrix2 = np.array([10, 20, 30])


In the code above, we have a 2x3 matrix (matrix1) and a 1-dimensional array (matrix2). If we want to add matrix2 to each row of matrix1, we can simply use the + operator

result = matrix1 + matrix2


The output will be

[[11 22 33]
[14 25 36]]


In this example, NumPy automatically broadcasts the 1-dimensional matrix2 to match the shape of matrix1, allowing element-wise addition to be performed.

## Adding a Custom Dimension to a Higher-dimensional Matrix

In addition to adding a custom dimension to a 2-dimensional matrix, you can also add a custom dimension to matrices with higher dimensions. The process remains the same; you just need to specify the desired position of the new axis.

Let's consider an example with a 3-dimensional matrix

matrix3d = np.array([[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]]])


Suppose we want to add a new dimension to the above 3-dimensional matrix at the end. We can use the np.newaxis attribute in a similar manner:

new_matrix3d = matrix3d[..., np.newaxis]


In the code above, ... is used to represent all the existing dimensions, and np.newaxis is inserted at the end. This will result in a 4-dimensional matrix.

## Reshaping the Matrix

Adding a custom dimension is often related to reshaping the matrix. NumPy provides a reshape function that allows you to change the shape of a matrix, including adding or removing dimensions. This function can be handy when you need to manipulate the structure of your matrix.

Here's an example of how to reshape a matrix and add a custom dimension −

matrix = np.array([[1, 2, 3],
[4, 5, 6]])

reshaped_matrix = matrix.reshape((2, 3, 1))


In the code above, the reshape function is used to change the shape of the matrix to (2, 3, 1). The added dimension at the end corresponds to the custom dimension we want to add.

## Conclusion

In this article, we explored additional concepts related to adding a custom dimension to a matrix using Python and NumPy. We discussed broadcasting, which allows arrays of different shapes to be operated on together, and saw how it can be useful when performing computations on matrices with added dimensions.

We also covered how to add a custom dimension to matrices with higher dimensions, as well as how to reshape a matrix and incorporate a custom dimension in the process. These techniques provide flexibility in manipulating matrices to suit specific needs.

By understanding these concepts and utilizing the tools provided by NumPy, you can efficiently work with matrices of various dimensions and perform complex computations.

Updated on: 14-Aug-2023

40 Views