Algorithm


  1. Input:

    • Take the input matrix.
  2. Initialization:

    • Get the number of rows and columns of the matrix.
  3. Create Transposed Matrix:

    • Create a new matrix to store the transposed values with dimensions swapped (rows become columns, and vice versa).
  4. 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).
  5. Output:

    • The transposed matrix is the result.
  6. 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

x
+
cmd
[12, 4, 3]
[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
Advertisements

Demonstration


Python Programing Example to Transpose a Matrix-DevsEnv