简体   繁体   English

Python numpy:矩阵乘法给出错误的结果

[英]Python numpy: Matrix multiplication giving wrong result

I'm using matrices in numpy python. 我在numpy python中使用矩阵。 I have a matrix A and I then I calculate its inverse. 我有一个矩阵A,然后我计算它的逆。 Now I multiply A with its inverse, and I'm not getting the identity matrix. 现在,我将A与它的逆相乘,但是我没有得到单位矩阵。 Can anyone point out what's wrong here? 谁能指出这是怎么回事?

A = matrix([
        [4, 3],
        [3, 2]
        ]);

print (A.I)        # prints [[-2  3], [ 3 -4]] - correct
print A.dot(A.T)   # prints [[25 18], [18 13]]     - Incorrect
print A*(A.T)      # prints [[25 18], [18 13]]     - Incorrect

You are using dot on the matrix and the transposed matrix (not the inverse) ... 您在矩阵和转置矩阵(不是逆矩阵)上使用点...

In [16]: np.dot(A.I, A)
Out[16]:
matrix([[ 1.,  0.],
        [ 0.,  1.]])

With the transposed you have the result you showed: 通过转置,您可以看到以下结果:

In [17]: np.dot(A.T, A)
Out[17]:
matrix([[25, 18],
        [18, 13]])

Here is another method: 这是另一种方法:

I works only on matrix I只在matrix

you can use np.linalg.inv(x) for inverse 您可以使用np.linalg.inv(x)进行inverse np.linalg.inv(x)

In [11]: import numpy as np

In [12]: A = np.array([[4, 3], [3, 2]])

In [13]: B = np.linalg.inv(A)

In [14]: A.dot(B)
Out[14]: 
array([[ 1.,  0.],
       [ 0.,  1.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM