Python Program to calculate the transpose of a matrix

In this simple python program, we need to find the transpose of a matrix. It's a matrix python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is the Transpose of a Matrix? 

In this basic python program, we explain how to calculate the transpose of a matrix. A matrix is a set of elements of the same data type arranged in rows and columns. Transpose of a matrix means we have to change the Rows into Columns and the Columns into Rows. It is flipping the diagonal of a matrix. The transpose of a matrix is denoted by matrix name raise T.

For example, let us take a simple example as A = [1, 2, 3] and the transpose of matrix A is AT = [1] [2] [3].

How we find the transpose in python? 

In this simple python program, we are using the predefined two matrices X and Y. Y is initialized to zeros to save the matrix X's transpose. Now we are using a nested for loop to traverse each row in the outer loop and each column in the inner loop of the given matrix. and then we assign the value of  X[i][j] to Y[j][i] until the loop iterations are over. Finally, print the result using a for loop in python.

ALGORITHM

STEP 1: Save the value for a matrix in the variable named X.

STEP 2: Initialize a Y matrix with interchange the order of matrix of A using python language.

STEP 3: Use an outer for loop to traverse through the matrix rows.

STEP 4: Use the inner for loop to traverse through the column of the matrix.

STEP 5: Assign the value of Y[j][i] = X[i][j] until all the iterations are over.

STEP 6: print the Y matrix using a for loop in a python programming language

Python Source Code

                                          X =[[1,2],  
   [4,5],  
   [7,8]]  
  
Y  = [[0,0,0],  
     [0,0,0]]  
  
for i in range(len(X)):  
   for j in range(len(X[0])):  
       Y[j][i] = X[i][j]  
  
for r in Y:  
   print(r)  
                                      

OUTPUT

[1, 4, 7]
[2, 5, 8]