Simple Matrix class

Paul McGuire ptmcg at austin.rr.com
Wed Jan 24 06:40:21 CET 2007


> The points should be aligned on a log-log plot to be a power function.
> As Robert Kern stated before, this problem should be not worse than
> O(n**3) - how have you implemented it?
>
Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05
X 3**n.

As for the implementation, it's pretty much brute force.  Here is the
code itself - the cacheValue decorator memoizes the calculated inverse
for the given Matrix.

    @cacheValue
    def det(self):
        "Function to return the determinant of the matrix."
        if self.isSquare():
            if self.numRows() > 2:
                multiplier = 1
                firstRow = self[1]
                tmp = self._rows[1:]
                rangelentmp = range(len(tmp))
                col = 0
                detsum = 0
                for val in firstRow:
                    if val:
                        #~ tmp2 = Matrix([
RowVector(t[0:col]+t[col+1:]) for t in tmp ])
                        tmp2 = self.getCachedMatrix([
RowVector(t[0:col]+t[col+1:]) for t in tmp ])
                        detsum += ( multiplier * val * tmp2.det() )
                    multiplier = -multiplier
                    col += 1
                return detsum
            if self.numRows() == 2:
                return self[1][1]*self[2][2]-self[1][2]*self[2][1]
            if self.numRows() == 1:
                return self[1][1]
            if self.numRows() == 0:
                return 0
        else:
            raise MatrixException("can only compute det for square
matrices")

    def cofactor(self,i,j):
        i-=1
        j-=1
        #~ tmp = Matrix([ RowVector(r[:i]+r[i+1:]) for r in
(self._rows[:j]+self._rows[j+1:]) ])
        tmp = self.getCachedMatrix([ RowVector(r[:i]+r[i+1:]) for r in
(self._rows[:j]+self._rows[j+1:]) ])
        if (i+j)%2:
            return -tmp.det()
        else:
            return tmp.det()
        #~ return (-1) ** (i+j) * tmp.det()

    @cacheValue
    def inverse(self):
        if self.isSquare():
            if self.det() != 0:
                ret = Matrix( [ RowVector( [ self.cofactor(i,j) for j
in self.colrange() ] )
                                 for i in self.rowrange() ] )
                ret *= (1.0/self.det())
                return ret
            else:
                raise MatrixException("cannot compute inverse for
singular matrices")
        else:
            raise MatrixException("can only compute inverse for square
matrices")




More information about the Python-list mailing list