NumPy – Using ndarray.trace() method (5 examples)

Updated: February 27, 2024 By: Guest Contributor Post a comment

Introduction

The NumPy library is a cornerstone in the Python ecosystem for scientific computing. Among its many features, the ndarray.trace() method is a lesser-known yet powerful function that can be used for various purposes such as calculating the trace of an array. This tutorial explores the ndarray.trace() method through five progressively sophisticated examples.

What is ndarray.trace() Used for?

Before diving into examples, let’s understand what trace is. In linear algebra, the trace of a square matrix is the sum of the elements on the main diagonal (from the top left to the bottom right). NumPy’s ndarray.trace() method extends this concept to arrays, allowing us to easily compute this sum. This method is primarily useful for square matrices but can be applied to arrays of higher dimensions as well.

Syntax:

numpy.ndarray.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)

Parameters:

  • offset: (Optional) Offset of the diagonal from the main diagonal. The default is 0.
  • axis1, axis2: (Optional) Axes to use as the first and second axes for computing the trace. The default is axes 0 and 1, respectively.
  • dtype: (Optional) Data type of the returned array. If not specified, the data type of the input array is used.
  • out: (Optional) Output array where the result is placed. If not provided, a new array is created.

Example 1: Basic Trace Calculation

Let’s start with the simplest use case: obtaining the trace of a 2D square matrix.

import numpy as np

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

# Calculating the trace
trace_value = matrix.trace()

# Output
print(f"Trace of the matrix: {trace_value}")

The output of this example is 15, which is the sum of the main diagonal elements 1, 5, 9.

Example 2: Trace With Offset

NumPy’s trace() method also allows calculating the trace with an offset from the main diagonal. This enables us to sum elements that are not exactly on the main diagonal but are offset by a certain number of elements to the right (positive offset) or left (negative offset).

import numpy as np

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

# Calculating the trace with an offset of 1
trace_value = matrix.trace(offset=1)

# Output
print(f"Trace with offset 1: {trace_value}")

The output here is 11, which corresponds to the sum of elements 2 and 9, located on the diagonal one position to the right of the main diagonal.

Example 3: Trace of a Higher-Dimensional Array

The trace() method can also be applied to higher-dimensional arrays, where it computes the trace by first collapsing the array into a matrix along axes specified by the user. This can be particularly useful in data science and signal processing applications.

import numpy as np

# Creating a 3D array
array_3d = np.array([[[1, 2, 3],
                      [4, 5, 6],
                      [7, 8, 9]],
                     [[10, 11, 12],
                      [13, 14, 15],
                      [16, 17, 18]]])

# Calculating the trace, collapsing the first two dimensions
trace_value = array_3d.trace(axis1=0, axis2=1)

# Output
print(f"Trace of the 3D array: {trace_value}")

Here, the output will be an array, specifically [21, 27, 33], indicating the traces of the individual matrices along the first two dimensions.

Example 4: Trace With Complex Numbers

NumPy comfortably handles arrays of complex numbers, allowing for the trace calculation of matrices comprising complex elements.

import numpy as np

# Creating a matrix with complex numbers
complex_matrix = np.array([[2 + 3j, 4],
                            [1, 3 - 4j]])

# Calculating the trace
trace_value = complex_matrix.trace()

# Output
print(f"Trace of the complex matrix: {trace_value}")

The output for this code snippet is 5 - 1j, which is indeed the sum of the main diagonal elements of the complex matrix.

Example 5: Applying Trace in Data Analysis

Finally, let’s see a practical application of the trace() method in data analysis. Suppose we have a large dataset represented as an array, and we want to calculate the covariance matrix’s trace to estimate the variance of data along its principal components.

import numpy as np

# Simulating a dataset
data = np.random.rand(100, 3)

# Computing the covariance matrix
cov_matrix = np.cov(data, rowvar=False)

# Calculating the trace of the covariance matrix to estimate variance
trace_value = cov_matrix.trace()

# Output
print(f"Estimated total variance: {trace_value}")

This produces an estimation of the total variance in the dataset across all principal components, demonstrating how the trace method can be instrumental in statistical analysis and data science.

Conclusion

This tutorial showcased the versatility of the ndarray.trace() method in NumPy, covering its applications from basic linear algebra to advanced data analysis techniques. As seen through the examples, understanding how to work with the trace function can greatly enhance your analytical capabilities in Python.