Programmin-in-Python

Multiplication of 2 Matrices

Dec 21st, 2020 (edited)
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. def transpose(Mat) :
  2.     T_mat = []
  3.    
  4.     for i in range(len(Mat[0])) :
  5.         temp = []
  6.         for j in range(len(Mat)) :
  7.             temp.append(Mat[j][i])
  8.         T_mat.append(temp)
  9.    
  10.     return T_mat
  11.  
  12. def main() :
  13.     row_1 = int(input("Enter the number of rows in the First Matrix : "))
  14.     col_1 = int(input("Enter the number of columns in the First Matrix : "))
  15.     row_2 = col_1
  16.     col_2 = int(input("\nEnter the number of columns in the Second Matrix : "))
  17.    
  18.     M1 , M2 , mul_mat = [],[],[]
  19.    
  20.     for i in range(row_1) :
  21.         temp = []
  22.         for j in range(col_1) :
  23.             elem = eval(input("Enter the Element of the First Matrix at the Position ; Row : {} , Column : {} =====> ".format(i+1,j+1)))
  24.             temp.append(elem)
  25.         M1.append(temp)
  26.    
  27.     print()
  28.     for i in range(row_2) :
  29.         temp = []
  30.         for j in range(col_2) :
  31.             elem = eval(input("Enter the Element of the Second Matrix at the Position ; Row : {} , Column : {} =====> ".format(i+1,j+1)))
  32.             temp.append(elem)
  33.         M2.append(temp)
  34.        
  35.     print("\nMatrix A : ")
  36.     for i in M1 :
  37.         for j in i :
  38.             print(j , end = "  ")
  39.         print()
  40.    
  41.     print("\nMatrix B : ")
  42.     for i in M2 :
  43.         for j in i :
  44.             print(j , end = '  ')
  45.         print()
  46.        
  47.     M2 = transpose(M2)
  48.    
  49.     for i in range(len(M1)) :
  50.         temp = []        
  51.         for j in range(len(M2)) :
  52.             sum_val = 0
  53.             for k in range(len(M2[0])) :
  54.                 sum_val += (M1[i][k] * M2[j][k])
  55.             temp.append(sum_val)
  56.         mul_mat.append(temp)
  57.    
  58.     print("\nMultiplication of A over B (A X B) : ")
  59.     for i in mul_mat :
  60.         for j in i :
  61.             print(j , end = '  ')
  62.         print()
  63.    
  64. main()
Add Comment
Please, Sign In to add comment