Here’s a Python program that transposes a matrix using nested loops

# Python program to transpose a matrix using nested loops # input matrix matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # get dimensions of the matrix rows = len(matrix) cols = len(matrix[0]) # create a new matrix to store the transposed matrix transposed_matrix = [] # iterate through each column of the original matrix for j in range(cols): # create a new row for the transposed matrix transposed_row = [] # iterate through each row of the original matrix for i in range(rows): # add the element at (i, j) to the new row transposed_row.append(matrix[i][j]) # add the new row to the transposed matrix transposed_matrix.append(transposed_row) # print the transposed matrix print("Original matrix:") for row in matrix: print(row) print("Transposed matrix:") for row in transposed_matrix: print(row)

In this program, we first define a 3×3 matrix as an example input. However, you could also take the matrix as input from the user.

We then get the dimensions of the matrix by finding the number of rows and columns. We use these dimensions to create a new empty matrix to store the transposed matrix.

We use nested loops to iterate through each column and row of the original matrix. For each element at (i, j), we add it to a new row in the transposed matrix at position (j, i).

Finally, we print both the original matrix and the transposed matrix using nested loops to iterate through each row and column of each matrix.

## Leave a Reply