1

I'm using the inverse matrix function inv() in Python. Im calculating the inverse of a 3x3 matrix, but when I multiply the result with the original matrix, I don't get the unity matrix, why?

Example:

AA = [[1,6,5],[2,3,1],[1,1,7]]

>>> inv(AA)
array([[-0.31746032,  0.58730159,  0.14285714],
[ 0.20634921, -0.03174603, -0.14285714],
[ 0.01587302, -0.07936508,  0.14285714]])

>>> inv(AA) * AA
array([[-0.31746032,  3.52380952,  0.71428571],
[ 0.41269841, -0.0952381 , -0.14285714],
[ 0.01587302, -0.07936508,  1.        ]])

>>> inv(AA) * AA
array([[-0.31746032,  3.52380952,  0.71428571],
[ 0.41269841, -0.0952381 , -0.14285714],
[ 0.01587302, -0.07936508,  1.        ]])

...which is not the unity matrix I. What am I missing?

piet.t
  • 11,718
  • 21
  • 43
  • 52
Victorynox
  • 11
  • 1
  • `print(np.dot(inv(AA),AA))` gives you the unity matrix. This is not Matlab, the `*` operator is element by element multiplication. – Hadi Farah Nov 19 '18 at 09:14

2 Answers2

3

You're doing element-wise multiplication, not matrix multiplication. Change your code to np.matmul(inv(AA), AA) or np.dot(inv(AA), AA) and you'll get the correct result

GPhilo
  • 18,519
  • 9
  • 63
  • 89
1

Python 3.5 introduced a new operator for matrix multiplication, so this could be:

from numpy.linalg import inv

AA = [[1,6,5],[2,3,1],[1,1,7]]

inv(AA) @ AA

which gives me:

array([[ 1.00000000e+00,  2.77555756e-17, -1.11022302e-16],
       [ 0.00000000e+00,  1.00000000e+00,  1.11022302e-16],
       [ 0.00000000e+00,  0.00000000e+00,  1.00000000e+00]])

which is about as close to unity as can be expected.

maybe relevant, see differences between @ and dot and other questions/answers linked there.

Sam Mason
  • 15,216
  • 1
  • 41
  • 60