Python Inverse of a Matrix

后端 未结 7 1111
遥遥无期
遥遥无期 2020-12-04 06:48

How do I get the inverse of a matrix in python? I\'ve implemented it myself, but it\'s pure python, and I suspect there are faster modules out there to do it.

7条回答
  •  独厮守ぢ
    2020-12-04 07:25

    For those like me, who were looking for a pure Python solution without pandas or numpy involved, check out the following GitHub project: https://github.com/ThomIves/MatrixInverse.

    It generously provides a very good explanation of how the process looks like "behind the scenes". The author has nicely described the step-by-step approach and presented some practical examples, all easy to follow.

    This is just a little code snippet from there to illustrate the approach very briefly (AM is the source matrix, IM is the identity matrix of the same size):

    def invert_matrix(AM, IM):
        for fd in range(len(AM)):
            fdScaler = 1.0 / AM[fd][fd]
            for j in range(len(AM)):
                AM[fd][j] *= fdScaler
                IM[fd][j] *= fdScaler
            for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
                crScaler = AM[i][fd]
                for j in range(len(AM)):
                    AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
                    IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
        return IM
    

    But please do follow the entire thing, you'll learn a lot more than just copy-pasting this code! There's a Jupyter notebook as well, btw.

    Hope that helps someone, I personally found it extremely useful for my very particular task (Absorbing Markov Chain) where I wasn't able to use any non-standard packages.

提交回复
热议问题