[Tutor] Matrix Multiplication and its Inverse

Steven D'Aprano steve at pearwood.info
Sat Jul 13 13:54:46 CEST 2013


On 13/07/13 05:05, Jack Little wrote:
> Is there a way in python to do matrix multiplication and its inverse? No external modules is preferred, but it is ok.


If you have numpy, you should use that.

If you want a pure Python version, here's a quick and dirty matrix multiplier that works only for 2x2 matrices.


def is_matrix(obj):
     if len(obj) == 2:
         return len(obj[0]) == 2 and len(obj[1]) == 2
     return False


def matrix_mult(A, B):
     """Return matrix A x B."""
     if not (is_matrix(A) and is_matrix(B)):
         raise ValueError('not matrices')
     [a, b], [c, d] = A
     [w, x], [y, z] = B
     return [[a*w + b*y, a*x + b*z],
             [c*w + d*y, c*x + d*z]]


I leave the inverse as an exercise :-)



-- 
Steven


More information about the Tutor mailing list