Skip to content

Instantly share code, notes, and snippets.

@douglas-vaz
Created April 21, 2014 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglas-vaz/11152983 to your computer and use it in GitHub Desktop.
Save douglas-vaz/11152983 to your computer and use it in GitHub Desktop.
Matrix operations in Python with a functional style
#!/usr/bin/python3
'''
Copyright (c) 2014 Douglas Vaz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
from functools import reduce
class Matrix:
def __init__(self, args):
self.__n__ = (len(args), len(args[0]))
self.__matrix__ = args
self.__square__ = False;
#Validate
for i in args:
assert(len(i) == self.__n__[1])
if self.__n__[0] == self.__n__[1]:
self.__square__ = True
def row(self, i):
assert(i < self.__n__[0])
return self.__matrix__[i]
def column(self, j):
assert(j < self.__n__[1])
return [col[j] for col in self.__matrix__]
def __add__(self, b):
assert(self.__n__ == b.__n__)
return Matrix([[i+j for i,j in zip(ai,bi)] for ai, bi in zip(self.__matrix__, b.__matrix__)])
def __sub__(self, b):
assert(self.__n__ == b.__n__)
return Matrix([[i-j for i,j in zip(ai,bi)] for ai, bi in zip(self.__matrix__, b.__matrix__)])
def __mul__(self, b):
assert(self.__n__[1] == b.__n__[0])
sum = lambda x,y: x + y
return Matrix([[reduce(sum, [aik*bkj for aik, bkj in zip(self.row(i),b.column(j)) ]) for j in range(b.__n__[1])] for i in range(self.__n__[0])])
def __truediv__(self, b):
return Matrix([[e/b for e in row] for row in self.__matrix__])
def transpose(self):
return Matrix([self.column(i) for i in range(self.__n__[0])])
def minor(self,i,j):
assert(i < self.__n__[0] and j < self.__n__[0])
mat = []
for m, row in enumerate(self.__matrix__):
r = [e for n,e in enumerate(row) if m != i and n != j]
if len(r) > 0:
mat.append(r)
return Matrix(mat)
def __str__(self):
return str(self.__matrix__)
def dimensions(self):
return self.__n__
def determinant(self):
assert(self.__square__)
if self.__n__[0] == 1:
return self.row(0)[0]
elif self.__n__[0] == 2:
return self.row(0)[0] * self.row(1)[1] - self.row(0)[1] * self.row(1)[0]
else:
sum = 0
for j,n in enumerate(self.row(0)):
sum = sum + pow(-1,j+2) * n * self.minor(0,j).determinant()
return sum
def cofactor(self):
assert(self.__square__)
m = []
for i,row in enumerate(self.__matrix__):
m.append([pow(-1,i+j+2) * self.minor(i,j).determinant() for j in range(self.__n__[0])])
return Matrix(m)
def adjoint(self):
assert(self.__square__)
return self.cofactor().transpose()
def inverse(self):
d = self.determinant()
assert(self.__square__ and d != 0)
return self.adjoint()/d
if __name__ == "__main__":
a = Matrix((( 5, 6,-1, 4),
( 3, 5, 2, 1),
(-1, 0, 3, 6)))
b = Matrix((( 2, 1),
( 4,-2),
( 7, 5),
( 3,-8)))
c = a * b
d = Matrix((( 2, 3, 1),
( 4, 5,-3),
(-1, 6, 7)))
print("A * B = C = ")
print(c)
print('\n')
print("C / 2 = ")
print(str(c/2))
print('\n')
print("Adj D = ")
print(d.adjoint())
print('\n')
print("|D| = ")
print(d.determinant())
print('\n')
print("Inverse D = ")
print(d.inverse())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment