Transpose of a given matrix using python

 


Statement:

Transpose of a matrix is the matrix obtained by converting either each rows into columns or each columns into rows.
You need to take input of a matrix from user and print the transpose of given matrix.


Difficulty: Medium
Topics covered : Nested loops in python and nested list in python


Code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'''
Python code to find transpose of a given matrix
Code by: Fox Stack
'''

r=int(input("Enter the number of rows in matrix: "))
c=int(input("Enter the number of coloumns in the matrix: "))

if r!=c:
    print("Transpose can only be find of square matrix")
    exit(0)
else:
    print("Enter elements of the matrix row wise:")
    print("\n")
    arr=[]
    transpose=[]
    arr2=[]

    for i in range(r):
        for j in range(c):
            a=int(input())
            arr2.append(a)
        arr.append(arr2)
        arr2=[]
    arr2=[]
    for i in range(r):
        for j in range(c):
            arr2.append(arr[j][i])
        transpose.append(arr2)
        arr2=[]
    
    print("Transpose of given matrix is: ")
    for i in range(r):
        for j in range(c):
            print(transpose[i][j],end=" ")
        print("\n")
    
    
Labels : #python ,

Post a Comment