from Matrix2D import * # Construct a 3x5 matrix M = Matrix2D.create(3,5) # Construct a 5x5 identity matrix I = Matrix2D.identity(5,5) # Multiply A times B A = Matrix2D.fromlist(2, [1,2, 3,4]) B = Matrix2D.fromlist(2, [4,3, 2,1]) C = A * B # equivalent to: C = A.multiply(B) print C.tolist() # [[8, 5], [20, 13]] assert C.tolist() == [[8, 5], [20, 13]] # Prove inverse I = B / B # eqiv to: I = B * B.inverse() assert B / B == Matrix2D.identity(2,2) # Multiply by scalar 2 A.apply_lambda( lambda x: x*2 ) print A.tolist() # [[2,4], [6,8]] assert A.tolist() == [[2,4], [6,8]] # Round everything to 2 decimal places A.apply_lambda( lambda x: round(x, 2) ) # Blank the diagonal with 0's # leave everything else untouched def f(row,col, value): if (row==col): return 0 A.apply_func(f) print A.tolist() # [[0,4], [6,0]] assert A.tolist() == [[0,4], [6,0]] # Get the dot-product of two vectors (at * b) a = Matrix2D.vector([1,2,3]) b = Matrix2D.vector([3,2,1]) c = a.t() * b print c.toscalar() # 10 assert c.toscalar() == 10 # Get dot product of A.row1 and B.col1 c = A.get_row(0) * B.get_col(0) print c.toscalar() # 8 assert c.toscalar() == 8.0