python - Creating a 2 x 2 matrix and finding its inverse -
class multidimensionalarray: def __init__(self, numrows, numcolumns): self.r = numrows self.c = numcolumns self.array = [[(x+3*y) x in range(self.r)] y in range(self.c)] self.inverse = [[]] def modifyitem(self, row, column, item): self.array[row][column] = item def getitem(self, row, column): print self.array[row][column] return self.array[row][column] def showarray(self): print self.array def changesize(self, rows, columns): self.r = rows self.c = columns self.array = [[(x+3*y) x in range(self.r)] y in range(self.c)] def getsize(self): print [self.r, self.c] return [self.r, self.c] def getinverse(self): if ((self.r == 2) , (self.c == 2)): = self.array[0][0] b = self.array[0][1] c = self.array[1][0] d = self.array[1][1] l in self.array: item in l: item = int(item) self.inverse[0][0] = d self.inverse[0][1] = b * (-1) self.inverse[1][0] = c * (-1) self.inverse[1][1] = self.inverse = self.inverse * (1 / (a*d - b*c)) print self.inverse return self.inverse mat = multidimensionalarray(2,2) mat.showarray() mat.getinverse()
this code gets stuck on following lines of code. error says "list assignment index out of range". goal make mathematical inverse of given 2x2 matrix. can me working? thanks
self.inverse[0][0] = d self.inverse[0][1] = b * (-1) self.inverse[1][0] = c * (-1) self.inverse[1][1] =
there 2 bugs.
first, define inverse self.inverse = [[]]
. has no element [0][0]
, hence exception. may write instead self.inverse = [[0] * numcolumns in range(numrows)]
initialize inverse 0 matrix.
the program fail on line self.inverse = self.inverse * (1 / (a*d - b*c))
: python not know how multiply list number. 1 way be
k = 1 / (a*d - b*c) self.inverse = [[x * k x in u] u in self.inverse]
notice b * (-1)
can written -b
.
apart that, class bit ugly, answer computed inverse correct. ugly, because matrix class not initialize predefined constant matrix, , inverse matrix, not member. guess there tests prepare better , more complete class.
to multiply elements of self.inverse "in place" (that is, without building new matrix):
for in range(numrows): j in range(numcolumns): self.inverse[i][j] *= k
you may this:
for row in self.inverse: j in range(numcolumns): row[j] *= k
Comments
Post a Comment