Write a program to transpose a matrix


Topic: Write a program to transpose a matrix

Solution

M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
if not isinstance(M[0], list):
    M = [M]
rows = len(M)
cols = len(M[0])
MT = []
while len(MT) < dim:
    MT.append([])
    while len(MT[-1]) < dim:
        MT[-1].append(0.0)
for i in range(rows):
    for j in range(cols):
        MT[j][i] = M[i][j]
print("Transpose Array")
for i in range(rows):
    row = '|'
    for b in range(cols):
        row = row + ' ' + str(MT[i][b])
    print(row + ' ' + '|')



List all Python Programs