To find the transpose of a given matrix

Question:

I have been trying to run the code but its giving error that – "list index out of range"

What is the reason?
And is there any other way to find the transpose of a matrix without using numpy

This is the code I wrote


n = int(input("Enter the size of square matrix"))
matrix = []
for i in range(n):  
   a =[]
   for j in range(n):  
       a.append(int(input("Enter the entries rowwise:")))
   matrix.append(a)
matrix1 = []
for i in range(0,n):
   b = []
   for j in range(0,n):
        matrix1[i][j] = matrix[j][i]

for i in range(n):
   for j in range(n):
        print(matrix1[i][j], end = " ")
print()

What is the reason for the error in the line matrix1[i][j] = matrix[j][i]?
And is there any other way to find the transpose of a matrix without using numpy

Asked By: iotainhills

||

Answers:

The matrix1 is a list of dim 1 you try to index it as it already is a 2-d list. Try to use the b list to append the elements of the transposed matrix and then append it to matrix1 like below:

n = int(input("Enter the size of square matrix"))
matrix = []
for i in range(n):  
   a =[]
   for j in range(n):  
       a.append(int(input("Enter the entries rowwise:")))
   matrix.append(a)
matrix1 = []
for i in range(0,n):
   b = []
   for j in range(0,n):
        b.append( matrix[j][i])
   matrix1.append(b)
for i in range(n):
   for j in range(n):
       print(matrix1[i][j], end = " ")
print()
Answered By: Orfeas Bourchas

You can use zip function also for transpose.

Example

Code:-

matrix=[[1,2,3],[4,5,6],[7,8,9]]
#print(matrix)
res=[]
for i in zip(*matrix):
    res.append(i)
print(res)

Output:-

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Answered By: Yash Mehta

If the name of the matrix is "matrix" just go with:

transposed = list(zip(*matrix))
Answered By: John Doe
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.