Python: Transpose Matrix

1. Introduction

Transposing a matrix involves swapping rows with columns. If you have a matrix that is m x n (m rows and n columns), its transpose will be n x m (n rows and m columns). Transposition is a fundamental operation in linear algebra and finds its applications in various domains, from computer graphics to machine learning. In this post, we will explore how to transpose a matrix in Python.

2. Program Overview

1. Define the matrix.

2. Use list comprehension to transpose the matrix.

3. Display the original and transposed matrix.

3. Code Program

# Python program to transpose a matrix

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

def transpose_matrix(mat):
    """Function to transpose a given matrix."""
    # Use list comprehension to get the transpose
    transposed = [[mat[j][i] for j in range(len(mat))] for i in range(len(mat[0]))]
    return transposed

# Get the transposed matrix
transposed_matrix = transpose_matrix(matrix)

# Display the matrices
print("Original Matrix:")
for row in matrix:
    print(row)

print("\nTransposed Matrix:")
for row in transposed_matrix:
    print(row)

Output:

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

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

4. Step By Step Explanation

1. A sample matrix of size 3x3 is defined for demonstration. This matrix can be changed to any other size or value.

2. The transpose_matrix function takes a matrix as an argument and uses list comprehension to generate the transposed matrix. It loops through columns for the outer loop and rows for the inner loop, essentially flipping the positions of elements.

3. The original and transposed matrices are then displayed using a simple loop.

4. In the provided output, the original matrix has its first row as [1, 2, 3], while the transposed matrix has its first column as [1, 2, 3], indicating the successful transposition of the matrix.

Comments