Practical No 3
Practical No 3
Practical No: 3
Write a python program to compute following computation on matrix:
d) Transpose of a matrix
def print_matrix(matrix):
print()
max_width = 0
item_width = len(str(item))
max_width = item_width
print()
print()
result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
`
row.append(A[i][j] + B[i][j])
result.append(row)
return result
result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j] - B[i][j])
result.append(row)
return result
rows_A = len(A)
cols_A = len(A[0])
cols_B = len(B[0])
result = []
for i in range(rows_A):
row = []
for j in range(cols_B):
value = 0
for k in range(cols_A):
row.append(value)
`
result.append(row)
return result
def transpose_matrix(matrix):
result = []
for i in range(len(matrix[0])):
row = []
for j in range(len(matrix)):
row.append(matrix[j][i])
result.append(row)
return result
A=[
[5, 2, 7],
[1, 3, 2],
[8, 9, 4]
B=[
[7, 1, 3],
[4, 5, 6],
[7, 8, 9]
]
`
print("Matrix A:")
print_matrix(A)
print("Matrix B:")
print_matrix(B)
print("Addition: A + B")
addition = add_matrices(A, B)
print_matrix(addition)
print("Subtraction: A - B")
subtraction = subtract_matrices(A, B)
print_matrix(subtraction)
print("Multiplication: A * B")
multiplication = multiply_matrices(A, B)
print_matrix(multiplication)
print("Transpose of A:")
transpose = transpose_matrix(A)
print_matrix(transpose)
`
Output:
Matrix A:
527
132
894
Matrix B:
713
456
789
Addition: A + B
12 3 10
5 8 8
15 17 13
Subtraction: A - B
-2 1 4
-3 -2 -4
1 1 -5
Multiplication: A * B
92 71 90
33 32 39
120 85 114
Transpose of A:
518
239
724