Python matrix query - must be simpler way
Question: I have created a small Python program to multiply two 2 by 2 matrices but am
wondering if it could be simplified in any way (particularly the creation of
new arrays)

The python code is below:

    
    
    matA=[0]*2
    matB=[0]*2
    matC=[0]*2
    matC[0]=[0]*2
    matC[1]=[0]*2
    # creating new arrays for multiplying two 2 by 2 matrices
    # must be a more simple way
    
    
    def multiply2by2matrices(a,b):
    
        matC[0][0]=a[0][0]*b[0][0]+a[0][1]*b[1][0]
        matC[0][1]=a[0][0]*b[0][1]+a[0][1]*b[1][1]
        matC[1][0]=a[1][0]*b[0][0]+a[1][1]*b[1][0]
        matC[1][1]=a[1][0]*b[0][1]+a[1][1]*b[1][1]
    
        print ((matC[0][0]),(matC[0][1]))
        print ((matC[1][0]),(matC[1][1]))
    
    matA[0]=[4,3]
    matA[1]=[2,12]
    
    matB[0]=[5,-2]
    matB[1]=[6,3]
    
    multiply2by2matrices(matA, matB)
    

Any thoughts will be greatly received.


Answer: Don't implement by hand. You are reinventing the wheel and there very good
wheels around already.

Numpy is the answer.

    
    
    import numpy as np
    a = np.arange(20).reshape(5,4)
    b = (np.arange(20) + 10).reshape(4,5)
    np.dot(a,b)
    

Docs:

<http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html>

Cheers, P

