In this tutorial, we will learn how to transpose a matrix in Python. We will cover the basic concept of matrix transposition and implement a function to perform the operation.
Matrix transposition is the process of swapping the rows and columns of a matrix. The element at row i
and column j
of the original matrix becomes the element at row j
and column i
in the transposed matrix.
The syntax to transpose a matrix in Python is:
def transpose_matrix(matrix):
transposed = []
for i in range(len(matrix[0])):
row = []
for j in range(len(matrix)):
row.append(matrix[j][i])
transposed.append(row)
return transposed
We can create a function to transpose a matrix by swapping its rows and columns.
For example,
transpose_matrix
that takes one parameter matrix
.transposed
to store the transposed matrix.for
loop to iterate through the elements of the matrix.j
and column i
of the original matrix to a new row.transposed
list.transposed
matrix.def transpose_matrix(matrix):
transposed = []
for i in range(len(matrix[0])):
row = []
for j in range(len(matrix)):
row.append(matrix[j][i])
transposed.append(row)
return transposed
# Sample matrix
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Transpose the matrix
result = transpose_matrix(matrix)
# Print the result
print('Transposed matrix is:')
for row in result:
print(row)
Transposed matrix is: [1, 4, 7] [2, 5, 8] [3, 6, 9]