Algorithm
-
Input:
- Take the input matrix.
-
Initialization:
- Get the number of rows and columns of the matrix.
-
Create Transposed Matrix:
- Create a new matrix to store the transposed values with dimensions swapped (rows become columns, and vice versa).
-
Transpose:
- Use nested loops to iterate through the original matrix.
- Place the value of the original matrix at position
(i, j)
into the transposed matrix at position(j, i)
.
-
Output:
- The transposed matrix is the result.
-
Display (Optional):
- If needed, display the original and transposed matrices.
Code Examples
#1 Code Example- Matrix Transpose using Nested Loop
Code -
Python Programming
# Program to transpose a matrix using a nested loop
X = [[12,7],
[4 ,5],
[3 ,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)
Copy The Code &
Try With Live Editor
Output
[12, 4, 3]
[7, 5, 8]
[7, 5, 8]
#2 Code Example- Matrix Transpose using Nested List Comprehension
Code -
Python Programming
''' Program to transpose a matrix using list comprehension'''
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]
for r in result:
print(r)
Copy The Code &
Try With Live Editor
Demonstration
Python Programing Example to Transpose a Matrix-DevsEnv