Write a program to Transpose a Matrix in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Program to transpose a matrix using nested loop X = [[12,7], [42 ,5], [32 ,8]] result = [[0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) |
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.