Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # Import required libraries
- from __future__ import division
- import sys
- import numpy as np
- def matrixTranspose(M):
- answer = [];
- answer = [ [row[n] for row in M] for n in range(len(M[0])) ]
- return answer;
- def identityMatrix(n):
- answer = [];
- answer = [ [int(i==j) for j in range(n)] for i in range(n) ];
- return answer;
- def vectorMatrixMultiplication(M,V):
- """
- Function multiplies a Matrix and a Vector
- Inputs:
- M: A matrix of length m x n (m rows, n columns)
- V: A vector of length n
- Output:
- answer: A vector of length m
- """
- answer = [];
- mLen = len(M);
- vLen = len(V);
- if ( (mLen == 0) or (vLen == 0) ) :
- raise ValueError("Matrix and Vector cannot be empty");
- elif ( len(M[0]) != vLen ) :
- raise ValueError("Number of columns of matrix M should equal length of vector V")
- answer = [ sum(row[n]*V[n] for n in range(vLen) ) for row in M]
- return answer
- def matrixMultiplication(M1, M2):
- """
- Function multiplies a Matrix and a Vector
- Inputs:
- M1: A matrix of length m x n (m rows, n columns)
- M2: A matrix of length n x p (n rows, p columns)
- Output:
- answer: A matrix of length m x p (m rows, p columns)
- """
- answer = [];
- m = len(M1);
- n = len(M2);
- p = len(M2[0]);
- if ( (m == 0) or (n == 0) ) :
- raise ValueError("Matrices cannot be empty");
- elif ( len(M1[0]) != n ) :
- raise ValueError("Number of columns of matrix M1 should equal number of rows of matrix M2")
- for n in range(p):
- vector = [ row[n] for row in M2];
- answer.append(vectorMatrixMultiplication(M1, vector) );
- return matrixTranspose(answer);
- matrix = [[1, 2, 3, 4], [10, 11, 12, 13]];
- vector = [5, 6, 7, 9];
- print "========= test vectorMatrixMultiplication =========";
- print "matrix: \n", np.matrix(matrix);
- print "vector: \n", vector;
- print "vectorMatrixMultiplication:";
- print vectorMatrixMultiplication(matrix,vector);
- matrix1 = [[1, 2, 3, 4], [10, 11, 12, 13]];
- matrix2 = [ [5,10], [6,11], [7,12], [9,13] ];
- print "========= test matrixMultiplication =========";
- print "matrix: \n", np.matrix(matrix1);
- print "matrix: \n", np.matrix(matrix2);
- print "matrixMultiplication:";
- print np.matrix(matrixMultiplication(matrix1, matrix2));
- print "========= test identityMatrix =========";
- print np.matrix(identityMatrix(4));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement