# Find the transpose of a matrix in Python Program

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a matrix, we need to display transpose of the matrix.

Transpose of a matrix is obtained by replacing the value present at A[i][j] by A[j][i].

Now let’s observe the concept in the implementation below−

## Approach 1: Creating a new matrix to store the transpose of the input matrix

### Example

Live Demo

def transpose(A,B):
for i in range(M):
for j in range(N):
B[i][j] = A[j][i]
# driver code
M = N = 4
A = [ [0, 1, 1, 0],
[0, 2, 0, 2],
[0, 3, 0, 3],
[0, 0, 4, 4]]
B = A[:][:] # empty matrix
transpose(A, B)
print("Transformed matrix is")
for i in range(N):
for j in range(N):
print(B[i][j], " ", end='')
print()

### Output

Transformed matrix is
0 0 0 0
0 2 3 0
0 3 0 4
0 0 4 4

## Approach 2: Storing the transpose into the input matrix

### Example

Live Demo

# function
def transpose(A):
for i in range(M):
for j in range(i+1, N):
A[i][j], A[j][i] = A[j][i], A[i][j]
M = N = 4
A = [ [0, 1, 1, 0],
[0, 2, 0, 2],
[0, 3, 0, 3],
[0, 0, 4, 4]]
transpose(A)
print("Transformed matrix is")
for i in range(M):
for j in range(N):
print(A[i][j], " ", end='')
print()

### Output

Transformed matrix is
0 0 0 0
0 2 3 0
0 3 0 4
0 0 4 4

## Conclusion

In this article, we have learned how we can transpose the matrix.

Advertisements