Matrix2D Readme
http://hurring.com/code/python/matrix2d/
@author Scott Hurring [scott at hurring dot com]
@version v0.3 - Apr 20, 2006
Originally, this was a quick hack i wrote to double check my
Linear algebra homework one night... since then, i've put some
more time into it and tried to make it a little more open-ended.
Version 0.3:
- Cleanup of matrix creation and initialization,
removed some redundant code and cleaned up the code.
- Added get_col() and get_row() and __eq__, and added
some code to make it easier to work with vectors (1d matrix).
I wrote this code for fun one night, so it's not optimized
or terribly well debugged. I use it to doublecheck my homework,
so i'm reasonably sure it'll work for most matrices, i can't
guarantee it wont fail or bomb out sometimes.
Useage Example
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
Older Versions