Python program that uses nested loops to transpose a given matrix
def transpose_matrix(matrix):
rows = len(matrix)
cols = len(matrix[0])
# Initialize result matrix with zeros
result = [[0 for j in range(rows)] for i in range(cols)]
for i in range(rows):
for j in range(cols):
result[j][i] = matrix[i][j]
return result
# Example usage
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(transpose_matrix(matrix))
The function transpose_matrix(matrix)
takes a 2D matrix as an argument. It first determines the number of rows and columns of the matrix using the len()
function. Then it creates a new 2D matrix with the number of rows and columns swapped, using list comprehension, and all elements initialized to 0. The nested for loop runs for the number of rows and columns and assigns the corresponding element of the input matrix to the transposed position of the new matrix. Finally, it returns the transposed matrix.
The example usage creates a matrix and calls the transpose_matrix()
function to transpose it, and then prints the resulting matrix.
You could also use zip()
function to transpose the matrix, which is a more efficient and pythonic way of transposing the matrix.
def transpose_matrix(matrix):
return [list(i) for i in zip(*matrix)]
This function uses the zip()
function along with the *
operator to unpack the rows of the matrix, and then the list()
function to convert the resulting tuples to lists, and finally it returns the transposed matrix.