Python

Python Program to Transpose a Matrix1 min read

Write a program to Transpose a Matrix in Python

This Python program transposes a matrix X using nested loops. The matrix X is defined as a list of lists with specific values. The result matrix is also defined as a list of lists with all elements initialized to 0.




The program uses two nested loops to iterate through the rows and columns of the matrix X.

The outer loop, “for i in range(len(X))”, iterates through the rows of the matrix X.

The inner loop, “for j in range(len(X[0]))”, iterates through the columns of the matrix X.

For each element in the matrix X, the program assigns the value of the element to the corresponding element in the result matrix but with the rows and columns switched.

After the nested loops have finished executing, the program uses another loop, “for r in result:”, to iterate through the rows of the result matrix and print each row.

The output is the transpose of the original matrix X, with rows and columns switched.

Leave a Comment