Write a program in python to transpose a matrix and print it.
Example:
1 2 3 4 5 6 | matrix = [[1,2,3], [4,5,6]] transpose = [[1,4], [2,5], [3,6]] |
In python, we represent a matrix using a nested list. For example matrix = [[1,2,3],[4,5,6]]
represent a matrix of order 2×3, in which matrix[i][j]
is the matrix element at ith row and jth column.
To transpose a matrix we have to interchange all its row elements into column elements and column elements into row elements.
To do that we first need to initialize a transpose matrix of order columnsXrows (of the original matrix) with zero, then loop through each element of the original matrix and assign the element to the transpose matrix as transpose[j][i] = matrix[i][j]
Let’s see the source code in python to transpose a matrix.
1 2 3 4 5 6 7 8 9 10 11 12 | matrix = [[1,2,3], [4,5,6]] transpose = [[0,0], [0,0], [0,0]] for i in range(len(matrix)): for j in range(len(matrix[0])): transpose[j][i] = matrix[i][j] print(transpose) |
Output
1 | [[1, 4], [2, 5], [3, 6]] |
In the above program len(matrix)
is the number of rows and len(matrix[0])
is the number of columns in the matrix.
If you have any doubts or suggestions then please comment below.