Problem: Write a program in Python to output transpose a matrix.
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 columns*rows (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.
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)): transpose[j][i] = matrix[i][j] print(transpose)
[[1, 4], [2, 5], [3, 6]]
In the above program,
len(matrix) returns the count of rows and
len(matrix) returns the count of columns in the matrix.