How to Calculate NumPy Trace of a Matrix using np.trace ?

This recipe will cover diverse techniques on how to accurately calculate the NumPy trace of the matrix for all your data science tasks.| ProjectPro

NumPy, a fundamental library for numerical computing in Python, provides a powerful function for calculating the trace of a matrix - np.trace. The trace of a matrix is the sum of its diagonal elements. Check out this numpy code example to learn what np.trace is, and how to Calculate NumPy Trace of a Matrix using np.trace, and even touch upon an alternative method to trace a matrix in Python without using NumPy.

What is np.trace in NumPy?

np.trace is a function in the NumPy library that calculates the sum of the diagonal elements of a matrix. Mathematically, the trace of an n×n matrix A is denoted as Tr(A) and is calculated as:

trace of a matrix

Here, Aii  represents the elements on the main diagonal of matrix A. Numpy simplifies this calculation with the np.trace() function, making it a convenient tool for matrix manipulation.

This operation is particularly useful in various mathematical and scientific applications, such as linear algebra and statistics. 

Partial Trace with np.trace 

The np.trace function can also be used to calculate the partial trace of a matrix. For instance, consider a bipartite system with a composite Hilbert space. To find the partial trace of one subsystem, use the following formula:

Partial trace NumPy

How to Calculate the Trace of a Matrix in NumPy?

Calculating the trace of a matrix in NumPy is straightforward using the np.trace function. Let's see a step-by-step guide:

Step 1 - Importing Library

    import numpy as np

We have only imported numpy which is needed.

Step 2 - Creating Matrix

We have created a matrix on which we will perform operations.

    matrix = np.array([[1, 2, 3],

                       [4, 5, 6],

                       [7, 8, 9],

                       [10, 11, 12]])

Step 3 - Calculating Trace of Matrix

We know that the trace of a matrix is calculated by summing the values of diagonals. So we have done the same to find the trace.

    print("Calculate the tracre of the matrix: ", matrix.diagonal().sum())

So the output comes as

Calculate the trace of the matrix:  15

How to Trace a Matrix in Python Without NumPy?

While np.trace is a powerful tool, you can trace a matrix in Python without using NumPy, albeit with more manual steps. Here's an example using a simple loop:

In this non-NumPy approach, we use a loop to iterate over the diagonal elements and sum them up. While this method works, NumPy's np.trace offers a more concise and efficient solution for numerical operations involving matrices.

Practice more NumPy Operations with ProjectPro! 

The ability to efficiently manipulate and analyze matrices is crucial in various applications, from machine learning to scientific research. This recipe has covered all the significance of the NumPy trace function and how it simplifies matrix operations. However, theoretical knowledge alone is not sufficient for true mastery. Practical experience through real-world projects is the key to solidifying your understanding and honing your skills. ProjectPro has a repository of over 250 hands-on projects in data science and big data, providing a platform for learners to apply their knowledge in a practical setting. Engaging in ProjectPro's projects not only reinforce your theoretical understanding but also help you gain insights into solving real-world problems. The platform offers a diverse range of projects, ensuring that you encounter challenges that mimic those found in the professional realm. This hands-on experience is crucial for building confidence and proficiency in utilizing NumPy and other tools when building data science projects.

Download Materials

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.

Build a Graph Based Recommendation System in Python -Part 1
Python Recommender Systems Project - Learn to build a graph based recommendation system in eCommerce to recommend products.

Recommender System Machine Learning Project for Beginners-1
Recommender System Machine Learning Project for Beginners - Learn how to design, implement and train a rule-based recommender system in Python

NLP Project to Build a Resume Parser in Python using Spacy
Use the popular Spacy NLP python library for OCR and text classification to build a Resume Parser in Python.

Loan Default Prediction Project using Explainable AI ML Models
Loan Default Prediction Project that employs sophisticated machine learning models, such as XGBoost and Random Forest and delves deep into the realm of Explainable AI, ensuring every prediction is transparent and understandable.

Build Piecewise and Spline Regression Models in Python
In this Regression Project, you will learn how to build a piecewise and spline regression model from scratch in Python to predict the points scored by a sports team.

Abstractive Text Summarization using Transformers-BART Model
Deep Learning Project to implement an Abstractive Text Summarizer using Google's Transformers-BART Model to generate news article headlines.

Build a Text Generator Model using Amazon SageMaker
In this Deep Learning Project, you will train a Text Generator Model on Amazon Reviews Dataset using LSTM Algorithm in PyTorch and deploy it on Amazon SageMaker.

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.