import numpy as np
# function inverse is defined to calculate the inverse
# matrix by solving LSE
def inverse(N,a):
z=[]
for i in range(N):
a0=a
b=[0 for j in range(N)]
b[i]=1
x=np.linalg.solve(a0, b)
I=np.dot(a, x)
z.append(x)
a1=np.array([z[i] for i in range(N)])
ai=a1.transpose()
return ai
a = np.array([[3,1], [1,2]])
ai=inverse(2,a)
print 'use inverse, ai_2x2=\n',ai
print 'np.linalg.inv(a)=\n',np.linalg.inv(a)
# solve 3x3 cy=d
c = np.array([[1,1,1], [3,1,0], [-1,0,1]])
ci=inverse(3,c)
print 'use inverse, ci_3x3=\n',ci
print 'np.linalg.inv(c)=\n',np.linalg.inv(c)
print 'check c dot ci=I=\n',np.dot(c, ci)