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. 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's NumPy library provides efficient and convenient tools for working with arrays, including matrices, along with a wide range of mathematical functions. We'll explore how to add custom dimensions to matrices using NumPy's powerful array manipulation capabilities.

Installing NumPy

Before we proceed, ensure NumPy is installed on your machine ?

pip install numpy

Creating a Basic Matrix

Let's start by creating a simple 3x3 matrix using NumPy ?

import numpy as np

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

print("Original Matrix:")
print(matrix)
print("Shape:", matrix.shape)
Original Matrix:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Shape: (3, 3)

Adding a Custom Dimension Using np.newaxis

To add a custom dimension to a matrix, we can use the numpy.newaxis attribute. This allows us to increase the dimensionality of an existing matrix by one ?

import numpy as np

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

# Adding a new dimension at different positions
new_matrix_axis1 = matrix[:, np.newaxis]  # Add dimension at axis 1
new_matrix_axis2 = matrix[np.newaxis, :]  # Add dimension at axis 0

print("Original Matrix Shape:", matrix.shape)
print("\nWith newaxis at axis 1:")
print("Shape:", new_matrix_axis1.shape)
print(new_matrix_axis1)

print("\nWith newaxis at axis 0:")
print("Shape:", new_matrix_axis2.shape)
print(new_matrix_axis2)
Original Matrix Shape: (3, 3)

With newaxis at axis 1:
Shape: (3, 1, 3)
[[[1 2 3]]

 [[4 5 6]]

 [[7 8 9]]]

With newaxis at axis 0:
Shape: (1, 3, 3)
[[[1 2 3]
  [4 5 6]
  [7 8 9]]]

Using np.expand_dims() Method

NumPy also provides the expand_dims() function which is more explicit for adding dimensions ?

import numpy as np

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

# Add dimension at different axes
expanded_axis0 = np.expand_dims(matrix, axis=0)  # Add at beginning
expanded_axis1 = np.expand_dims(matrix, axis=1)  # Add in middle
expanded_axis2 = np.expand_dims(matrix, axis=2)  # Add at end

print("Original shape:", matrix.shape)
print("Expanded at axis 0:", expanded_axis0.shape)
print("Expanded at axis 1:", expanded_axis1.shape)
print("Expanded at axis 2:", expanded_axis2.shape)
Original shape: (2, 3)
Expanded at axis 0: (1, 2, 3)
Expanded at axis 1: (2, 1, 3)
Expanded at axis 2: (2, 3, 1)

Reshaping to Add Dimensions

The reshape() function allows you to change the shape of a matrix, including adding dimensions ?

import numpy as np

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

# Reshape to add a custom dimension
reshaped_matrix = matrix.reshape((2, 3, 1))

print("Original shape:", matrix.shape)
print("Reshaped matrix shape:", reshaped_matrix.shape)
print("\nReshaped matrix:")
print(reshaped_matrix)
Original shape: (2, 3)
Reshaped matrix shape: (2, 3, 1)

Reshaped matrix:
[[[1]
  [2]
  [3]]

 [[4]
  [5]
  [6]]]

Practical Example: Broadcasting with Custom Dimensions

Adding dimensions is particularly useful for broadcasting operations ?

import numpy as np

# Create matrices for broadcasting
matrix1 = np.array([[1, 2, 3],
                    [4, 5, 6]])

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

# Add dimension to matrix2 for explicit broadcasting
matrix2_expanded = matrix2[np.newaxis, :]

print("Matrix1 shape:", matrix1.shape)
print("Matrix2 original shape:", matrix2.shape)
print("Matrix2 expanded shape:", matrix2_expanded.shape)

# Broadcasting addition
result = matrix1 + matrix2  # Automatic broadcasting
result_explicit = matrix1 + matrix2_expanded  # Explicit broadcasting

print("\nResult with automatic broadcasting:")
print(result)
print("\nResult with explicit broadcasting:")
print(result_explicit)
Matrix1 shape: (2, 3)
Matrix2 original shape: (3,)
Matrix2 expanded shape: (1, 3)

Result with automatic broadcasting:
[[11 22 33]
 [14 25 36]]

Result with explicit broadcasting:
[[11 22 33]
 [14 25 36]]

Comparison of Methods

Method Syntax Best For
np.newaxis array[:, np.newaxis] Quick dimension addition
np.expand_dims() np.expand_dims(array, axis=1) Explicit and readable code
reshape() array.reshape(new_shape) Complete shape transformation

Conclusion

Adding custom dimensions to matrices in Python is essential for advanced mathematical operations and machine learning algorithms. Use np.newaxis for quick additions, expand_dims() for clarity, and reshape() for complete transformations. These techniques enable efficient broadcasting and tensor operations in scientific computing.

Updated on: 2026-03-27T12:33:23+05:30

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements