Advertisement
Guest User

Untitled

a guest
Apr 26th, 2015
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. #!/usr/bin/python
  2. # Import required libraries
  3. from __future__ import division
  4. import sys
  5. import numpy as np
  6.  
  7.  
  8. def matrixTranspose(M):
  9. answer = [];
  10. answer = [ [row[n] for row in M] for n in range(len(M[0])) ]
  11. return answer;
  12.  
  13. def identityMatrix(n):
  14. answer = [];
  15. answer = [ [int(i==j) for j in range(n)] for i in range(n) ];
  16. return answer;
  17.  
  18. def vectorMatrixMultiplication(M,V):
  19. """
  20. Function multiplies a Matrix and a Vector
  21. Inputs:
  22. M: A matrix of length m x n (m rows, n columns)
  23. V: A vector of length n
  24. Output:
  25. answer: A vector of length m
  26. """
  27. answer = [];
  28. mLen = len(M);
  29. vLen = len(V);
  30.  
  31. if ( (mLen == 0) or (vLen == 0) ) :
  32. raise ValueError("Matrix and Vector cannot be empty");
  33. elif ( len(M[0]) != vLen ) :
  34. raise ValueError("Number of columns of matrix M should equal length of vector V")
  35.  
  36. answer = [ sum(row[n]*V[n] for n in range(vLen) ) for row in M]
  37.  
  38. return answer
  39.  
  40.  
  41.  
  42. def matrixMultiplication(M1, M2):
  43. """
  44. Function multiplies a Matrix and a Vector
  45. Inputs:
  46. M1: A matrix of length m x n (m rows, n columns)
  47. M2: A matrix of length n x p (n rows, p columns)
  48. Output:
  49. answer: A matrix of length m x p (m rows, p columns)
  50. """
  51. answer = [];
  52.  
  53. m = len(M1);
  54. n = len(M2);
  55. p = len(M2[0]);
  56.  
  57. if ( (m == 0) or (n == 0) ) :
  58. raise ValueError("Matrices cannot be empty");
  59. elif ( len(M1[0]) != n ) :
  60. raise ValueError("Number of columns of matrix M1 should equal number of rows of matrix M2")
  61.  
  62. for n in range(p):
  63. vector = [ row[n] for row in M2];
  64. answer.append(vectorMatrixMultiplication(M1, vector) );
  65.  
  66. return matrixTranspose(answer);
  67.  
  68.  
  69.  
  70. matrix = [[1, 2, 3, 4], [10, 11, 12, 13]];
  71. vector = [5, 6, 7, 9];
  72.  
  73. print "========= test vectorMatrixMultiplication =========";
  74. print "matrix: \n", np.matrix(matrix);
  75. print "vector: \n", vector;
  76. print "vectorMatrixMultiplication:";
  77. print vectorMatrixMultiplication(matrix,vector);
  78.  
  79.  
  80. matrix1 = [[1, 2, 3, 4], [10, 11, 12, 13]];
  81. matrix2 = [ [5,10], [6,11], [7,12], [9,13] ];
  82.  
  83. print "========= test matrixMultiplication =========";
  84. print "matrix: \n", np.matrix(matrix1);
  85. print "matrix: \n", np.matrix(matrix2);
  86. print "matrixMultiplication:";
  87. print np.matrix(matrixMultiplication(matrix1, matrix2));
  88.  
  89. print "========= test identityMatrix =========";
  90. print np.matrix(identityMatrix(4));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement