Transpose of matrix in python

Transpose of matrix in python

Transpose of a matrix is an operator that flips a matrix over its diagonal; i.e. it switches the row and column indices of a matrix by producing another matrix which is called the transpose of the matrix.

For example,



Order of matrix A => 3x3


Order of transpose of matrix A => 3x3




In the above example, the transpose matrix is achieved by assigning A[i][j] to 
AT[j][i].

Procedure :

1. Start.
2. Get the matrix as input from the user.
3. Initialize the transpose matrix.
4. loop ( 0 to number of rows)
    => loop (0 to number of columns)
        => transpose[j][i] = matrix[i][j]
5. print the transpose matrix.
6. End


Code :

#function to print matrix
def printMatrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i][j], end=" ")
print()

#Get the number of rows from user
n = int(input("Enter the number of rows : "))
m = int(input("Enter the number of columns : "))
#initialize a matrix(list)
matrix = []
for row in range(n):
        #Get the elements of a row separated by space and store in a list
l = list(map(int,input("Enter elements of row separated by space : ").split(" ")))
        #append the list to the matrix list
matrix+=[l]
#initialize the transpose matrix
transpose = [[0 for x in range(n)] for y in range(m)]
#  transpose of matix
for i in range(n) :
for j in range (m):
transpose[j][i] = matrix[i][j]
#print the matrix
printMatrix(transpose)

Sample input :


=> Matrix A



Sample output :


   => Transpose of matrix A



Output screenshot :

transpose of matrix in python
transpose - output




Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

What's your name, Tuple - HackerRank solution in python