Advertisement
Guest User

Untitled

a guest
Apr 25th, 2015
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. import numpy as np
  2.  
  3. # Define matrix and vector
  4. vector = [1, 2, 3, 4]
  5. matrix = [ [1, 2, 3, 4],
  6. [5, 6, 7, 8],
  7. [9, 0, 1, 2] ]
  8.  
  9. # Function 1
  10. def vectorMatrixMultiplication(matrix,vector):
  11. """
  12. Iterate over matrix rows with for loop
  13. Set an answer variable
  14. For each vector, multiply vector by corresponding matrix integer in row
  15. Sum the resulting 4 outputs of the row
  16. Set answer equal to output
  17. """
  18. answerList = []
  19. for x in range(len(matrix)):
  20. answer = 0
  21. for y in range(len(vector)):
  22. answer = answer + vector[y] * matrix[x][y]
  23. answerList.append(answer)
  24. print answerList
  25.  
  26.  
  27. # Function 2
  28. def matrixMutiplication(matrix1, matrix2):
  29. """
  30. Same methodology as above
  31. One additional loop required to iterate over the second matrix rows
  32. """
  33. answerMatrix=[]
  34. for x in range(len(matrix1)):
  35. answerList = []
  36. for y in range(len(matrix2)):
  37. answer = 0
  38. for z in range(len(matrix2[y])):
  39. answer = answer + matrix2[y][z] * matrix2[x][z]
  40. answerList.append(answer)
  41. answerMatrix.append(answerList)
  42.  
  43. print np.matrix(answerMatrix)
  44.  
  45. # Call functions
  46. vectorMatrixMultiplication(matrix,vector)
  47. matrixMutiplication(matrix, matrix)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement