I fixed it.
Still don't understand why my matrix keeps getting changed when I call the inverse() function.
Spoiler
class Matrix(object):
def __init__(self, twoDarray):
self.validate(twoDarray)
self.row = len(twoDarray)
self.col = len(twoDarray[0])
self.matrix = twoDarray
def validate(self, twoDarray):
for i in range(len(twoDarray)):
for j in range(len(twoDarray[0])):
if ((not isinstance(twoDarray[i][j], int) and not isinstance(twoDarray[i][j], float)) or not len(twoDarray[i]) == len(twoDarray[0])):
raise Exception("Error: invalid matrix.")
def __str__(self):
return "\n".join("".join(([str(self.matrix[j][i]).rjust(self.padding(i)+1) for i in range(self.col)])) for j in range(self.row))
def padding(self, i):
length = 0
for j in range(self.row):
if(len(str(self.matrix[j][i])) > length):
length = len(str(self.matrix[j][i]))
return length
def __add__(self, other):
if (other.row != self.row or other.col != self.col):
raise Exception("Error: cannot add matrices of different dimensions.")
result = [[0 for j in range (self.col)] for i in range (self.row)]
for i in range(self.row):
for j in range(self.col):
result[i][j] = self.matrix[i][j] + other.matrix[i][j]
newMatrix = Matrix(result)
return newMatrix
def __sub__(self, other):
if (other.row != self.row or other.col != self.col):
raise Exception("Error: cannot subtract matrices of different dimensions.")
result = [[0 for j in range (self.col)] for i in range (self.row)]
for i in range(self.row):
for j in range(self.col):
result[i][j] = self.matrix[i][j] - other.matrix[i][j]
newMatrix = Matrix(result)
return newMatrix
def __mul__(self, other):
if (isinstance(other, int) or isinstance(other, float)):
return self.scalarMul(other)
if (other.row != self.col):
raise Exception("Error: cannot multiply matrices of such dimensions.")
result = [[0 for j in range (other.col)] for i in range (self.row)]
for i in range(len(result[0])):
for j in range(self.col):
for k in range(len(result)):
result[k][i] += self.matrix[k][j] * other.matrix[j][i]
newMatrix = Matrix(result)
return newMatrix
def scalarMul(self, scalar):
result = [[0 for j in range (self.col)] for i in range (self.row)]
for i in range(self.col):
for j in range(self.row):
result[i][j] = self.matrix[i][j] * scalar
newMatrix = Matrix(result)
return newMatrix
def getEntry(self, i, j):
return self.matrix[i][j]
def setEntry(self, i, j, val):
self.matrix[i][j] = val
def getCol(self):
return self.col
def getRow(self):
return self.row
def transpose(self):
transpose = [[0 for j in range (self.row)] for i in range (self.col)]
for i in range(self.row):
for j in range(self.col):
transpose[j][i] = self.matrix[i][j]
newMatrix = Matrix(transpose)
return newMatrix
def isSquare(self):
return self.col == self.row
def isUpperTriangular(self):
if (not self.isSquare()):
return False
for i in range(self.row):
for j in range(i):
if (self.matrix[i][j] != 0):
return False
return True
def isLowerTriangular(self):
if (not self.isSquare()):
return False
for i in range(self.row):
for j in range(i+1, self.col):
if (self.matrix[i][j] != 0):
return False
return True
def isDiagonal(self):
return self.isLowerTriangular() and self.isUpperTriangular()
def inverse(self):
if(not self.isSquare()):
raise Exception("Error: cannot inverse a non-square matrix.")
return Matrix(self.invert())
def invert(self):
matrix = self.matrix
identity = self.identity(self.col).matrix
for i in range(self.col):
j = i
maxVal = matrix[i][j]
maxInd = i
for k in range(i+1, self.row):
if (abs(matrix[k][j]) > abs(maxVal)):
maxVal = matrix[k][j]
maxInd = k
if (maxVal != 0):
self.pivot(matrix, identity, i, maxInd)
for l in range(self.col):
matrix[i][l] /= maxVal
identity[i][l] /= maxVal
for m in range(self.row):
if (m == i):
continue
mul = matrix[m][i]
for n in range(self.col):
matrix[m][n] -= mul*matrix[i][n]
identity[m][n] -= mul*identity[i][n]
return identity
def pivot(self, matrix, identity, i, maxInd):
temp = matrix[i]
matrix[i] = matrix[maxInd]
matrix[maxInd] = temp
temp = identity[i]
identity[i] = identity[maxInd]
identity[maxInd] = temp
def identity(self = None, dim = None):
if (dim == None and not isinstance(self, int)):
if(not self.isSquare()):
raise Exception("Error: cannot inverse a non-square matrix.")
dim = self.col
if (isinstance(self, int)):
dim = self
def diag(row, col):
if (row == col):
return 1
return 0
return Matrix([[diag(row, col) for col in range(dim)] for row in range(dim)])
#-------------------------------------------------------------------------------
class Vector(object):
def __init__(self, array):
self.validate(array)
self.vector = array
self.dim = len(array)
def validate(self, array):
for i in range(len(array)):
if (not isinstance(array[i], int) and not isinstance(array[i], float)):
raise Exception("Error: invalid vector.")
def __str__(self):
return (" ".join([str(i) for i in self.vector]))
def __add__(self, other):
if (self.dim != other.dim):
raise Exception("Error: cannot add vectors of different dimensions.")
result = [0 for i in range(self.dim)]
for i in range(dim):
result[i] = self.vector[i] + other.vector[i]
return Vector(result)
def __sub__(self, other):
if (self.dim != other.dim):
raise Exception("Error: cannot subtract vectors of different dimensions.")
result = [0 for i in range(self.dim)]
for i in range(dim):
result[i] = self.vector[i] - other.vector[i]
return Vector(result)
def __mul__(self, other):
if (isinstance(other, int) or isinstance(other, float)):
return self.scalarMul(other)
if (self.dim != other.dim):
raise Exception("Error: cannot perform dot product on vectors of different dimensions.")
result = 0
for i in range(self.dim):
result += self.vector[i] * other.vector[i]
return result
def scalarMul(self, scalar):
result = [0 for i in range(self.dim)]
for i in range(self.dim):
result[i] = self.vector[i] * scalar
return Vector(result)
I can now do this:
B = Matrix.identity(5)
A = B.identity()
And B should be equal to A but in order to make that possible I had to modify the identity() function... because Python doesn't allow function overloading.
This post has been edited by carnivroar: 24 July 2012 - 02:30 PM

New Topic/Question
Reply




MultiQuote


|