furas

Python - Matrixes Multiplication (reddit.com)

Nov 1st, 2016
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. #
  4. # https://www.reddit.com/r/learnpython/comments/5ai9vf/my_code_only_takes_square_matrixes_why/
  5. #
  6.  
  7. print("\nEnter the value of row and column of first matrix :")
  8.  
  9. r1 = int(input("Rows: "))
  10. c1 = int(input("Columns: "))
  11.  
  12. # to make a blank X matrix:
  13. X = [[0 for column in range(c1)] for row in range(r1)]
  14.  
  15. print("\nEnter elements of first matrix : ")
  16.  
  17. for row in range(r1):
  18.     for column in range(c1):
  19.         X[row][column] = int(input("[{},{}]: ".format(row, column)))
  20.  
  21. #----------------------------------------------------------------
  22.        
  23. print("\nEnter the value of row and column of second matrix : ")
  24.  
  25. r2 = int(input("Rows: "))
  26. c2 = int(input("Columns: "))
  27.  
  28. # to make blank Y matrix:
  29. Y =[[0 for column in range(c2)] for row in range(r2)]
  30.  
  31. print("\nEnter elements of second matrix : ")
  32.  
  33. for row in range(r2):
  34.     for column in range(c2):
  35.         Y[row][column] = int(input("[{},{}]: ".format(row, column)))
  36.  
  37. #----------------------------------------------------------------
  38.  
  39. print("\nElements of First matrix is : ")
  40.  
  41. for row in X:
  42.     print(row)
  43.  
  44. print("\nElements of Second matrix is :")
  45.  
  46. for row in Y:
  47.     print(row)
  48.  
  49. #----------------------------------------------------------------
  50.  
  51. # result takes the result raw and column to make a blank result matrix
  52. result = [[0 for column in range(c1)] for row in range(r2)]
  53.  
  54. for row in range(len(X)):
  55.     for column in range(len(Y[0])):
  56.         for k in range(len(Y)):
  57.             result[row][column] += X[row][k] * Y[k][column]
  58.  
  59. print("\nMATRIX MULTIPLICATION:")
  60.  
  61. for row in result:
  62.     print(row)
Add Comment
Please, Sign In to add comment