Write a Python program to transpose a matrix.
The transpose of a matrix is obtained by swapping the rows and columns of the matrix. In other words, the element at position (i, j)
in the original matrix will move to position (j, i)
in the transposed matrix.
Input-Output Examples
plaintext
Example 1:
Input:
Matrix A:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output:
The transposed matrix is:
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
Example 2:
Input:
Matrix B:
[[1, 2],
[3, 4],
[5, 6]]
Output:
The transposed matrix is:
[[1, 3, 5],
[2, 4, 6]]
Algorithm to transpose a matrix
- Start
- Define the matrix: Initialize the matrix to be transposed.
- Check matrix dimensions: Determine the number of rows and columns in the matrix.
- Initialize a result matrix: Create an empty matrix with dimensions swapped (rows become columns, and columns become rows).
- Loop through rows and columns: Use nested loops to assign the elements from the original matrix to the transposed matrix.
- Store the result: Swap the element positions
(i, j)
to(j, i)
in the transposed matrix. - Display the result: Print the transposed matrix.
- End
Python Program to transpose a matrix
python
# Python program to transpose a matrix
# Define the matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Initialize an empty matrix for the transpose with swapped dimensions
transpose = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# Loop through rows and columns to transpose the matrix
for i in range(len(matrix)): # Loop through rows of the original matrix
for j in range(len(matrix[0])): # Loop through columns of the original matrix
transpose[j][i] = matrix[i][j]
# Display the transposed matrix
print("The transposed matrix is:")
for row in transpose:
print(row)
Code Explanation
- Defining the matrix:
The matrixmatrix
is a 3x3 matrix, represented as a 2D list in Python. This is the matrix that will be transposed. - Initializing the transpose matrix:
A new matrixtranspose
is initialized with the dimensions of the original matrix but with the rows and columns swapped. This matrix will store the transposed elements. - Looping through rows and columns:
The program uses two nested loops:- The outer loop iterates over the rows of the original matrix.
- The inner loop iterates over the columns of the original matrix. During each iteration, the element at position
(i, j)
in the original matrix is assigned to position(j, i)
in the transposed matrix.
- Displaying the output:
After the matrix is transposed, the program uses afor
loop to print each row of the transposed matrix.