Python Program - Transpose a Matrix

http‮.www//:s‬theitroad.com

here's a Python program that transposes a matrix:

# Define a matrix
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Print the original matrix
print("Original matrix:")
for row in matrix:
    print(row)

# Transpose the matrix
transposed = []
for i in range(len(matrix[0])):
    transposed.append([row[i] for row in matrix])

# Print the transposed matrix
print("Transposed matrix:")
for row in transposed:
    print(row)

In this program, we define a 3x3 matrix called matrix. To print the original matrix, we use a for loop to iterate over each row of the matrix and print it.

To transpose the matrix, we first create an empty list called transposed. We then use another for loop to iterate over the columns of the matrix (which are the same as the rows of the transposed matrix).

For each column, we use a list comprehension to create a new row in the transposed matrix. The list comprehension iterates over each row of the original matrix and adds the corresponding element from the current column to the new row.

We then append the new row to the transposed list.

Finally, we print the transposed matrix using another for loop to iterate over each row and print it.

If we run this program, the output will be:

Original matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transposed matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

Note that the matrix in this program is represented as a list of lists, where each inner list represents a row of the matrix. If you have a matrix represented as a 2D NumPy array, you can use the numpy.transpose() function to transpose it:

import numpy as np

# Define a matrix
matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

# Print the original matrix
print("Original matrix:")
print(matrix)

# Transpose the matrix
transposed = np.transpose(matrix)

# Print the transposed matrix
print("Transposed matrix:")
print(transposed)

This program produces the same output as the previous program, but uses NumPy to represent and transpose the matrix.