Site icon Student Projects Live

Python Program to Transpose a Matrix

Python Program to Transpose a Matrix

The provided Python program is designed to transpose a given matrix. Transposing a matrix involves swapping its rows and columns. The program defines a function called transpose_matrix that takes a matrix as input and returns its transpose. The function creates a new matrix with dimensions swapped (number of rows becomes the number of columns and vice versa) and then iterates through the elements of the original matrix, assigning them to the corresponding positions in the transposed matrix. The example usage section demonstrates how to use this function with a sample matrix, where the original and transposed matrices are printed to the console. Users can replace the example_matrix with their own matrices to obtain the transpose of different matrices using this program.


Source code

def transpose_matrix(matrix):
    # Get the number of rows and columns in the original matrix
    rows, cols = len(matrix), len(matrix[0])

    # Create a new matrix with swapped rows and columns
    transposed_matrix = [[0 for _ in range(rows)] for _ in range(cols)]

    # Populate the transposed matrix
    for i in range(rows):
        for j in range(cols):
            transposed_matrix[j][i] = matrix[i][j]

    return transposed_matrix

# Example usage:
# Replace this example matrix with your own matrix
example_matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

transposed_result = transpose_matrix(example_matrix)

# Print the original and transposed matrices
print("Original Matrix:")
for row in example_matrix:
    print(row)

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

Description

Certainly! Here’s a step-by-step description of the provided Python program:

  1. Function Definition (transpose_matrix):
  1. Determine Matrix Dimensions:
  1. Create Transposed Matrix:
  1. Populate Transposed Matrix:
  1. Return Transposed Matrix:
  1. Example Usage:
  1. Print Original and Transposed Matrices:
  1. Run the Program:

Users can modify the example_matrix or use the transpose_matrix function with their own matrices to obtain the transposed result.


Screenshot

Output:


Download

Exit mobile version