使用numpy逆矩阵 [英] Inverse of a matrix using numpy
问题描述
我想用numpy计算逆.但是我遇到了一个错误:
I'd like to use numpy to calculate the inverse. But I'm getting an error:
'numpy.ndarry' object has no attribute I
要计算numpy中矩阵的逆,例如矩阵M,它应该很简单:
print M.I
To calculate inverse of a matrix in numpy, say matrix M, it should be simply:
print M.I
代码如下:
x = numpy.empty((3,3), dtype=int)
for comb in combinations_with_replacement(range(10), 9):
x.flat[:] = comb
print x.I
我想是因为x现在是平坦的,所以发生此错误,因此'I
'命令不兼容.有没有解决的办法?
I'm presuming, this error occurs because x is now flat, thus 'I
' command is not compatible. Is there a work around for this?
我的目标是打印所有可能的数值矩阵组合的逆矩阵.
My goal is to print the INVERSE MATRIX of every possible numerical matrix combination.
推荐答案
I
属性仅存在于matrix
对象上,而不存在于ndarray
s上.您可以使用 numpy.linalg.inv
进行反转数组:
The I
attribute only exists on matrix
objects, not ndarray
s. You can use numpy.linalg.inv
to invert arrays:
inverse = numpy.linalg.inv(x)
请注意,生成矩阵的方式并非全部都是可逆的.您要么需要更改生成矩阵的方式,要么跳过那些不可逆的矩阵.
Note that the way you're generating matrices, not all of them will be invertible. You will either need to change the way you're generating matrices, or skip the ones that aren't invertible.
try:
inverse = numpy.linalg.inv(x)
except numpy.linalg.LinAlgError:
# Not invertible. Skip this one.
pass
else:
# continue with what you were doing
此外,如果要使用从[0,10)绘制的元素遍历所有3x3矩阵,则需要以下条件:
Also, if you want to go through all 3x3 matrices with elements drawn from [0, 10), you want the following:
for comb in itertools.product(range(10), repeat=9):
而不是combinations_with_replacement
,否则您将跳过类似
rather than combinations_with_replacement
, or you'll skip matrices like
numpy.array([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
这篇关于使用numpy逆矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!