我想用numpy来计算倒数。但是我得到了一个错误:
'numpy.ndarry' object has no attribute I
要计算numpy中的矩阵的逆,例如矩阵M,它应该简单地表示为: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
‘命令不兼容。有没有解决这个问题的办法?
我的目标是打印每个可能的数值矩阵组合的逆矩阵。
发布于 2014-02-08 06:32:07
I
属性仅存在于matrix
对象上,而不存在于ndarray
对象上。您可以使用numpy.linalg.inv
来反转数组:
inverse = numpy.linalg.inv(x)
请注意,您生成矩阵的方式并不是所有矩阵都是可逆的。你要么需要改变生成矩阵的方式,要么跳过那些不可逆的矩阵。
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矩阵,则需要以下内容:
for comb in itertools.product(range(10), repeat=9):
而不是combinations_with_replacement
,否则您将跳过如下矩阵
numpy.array([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
发布于 2017-02-22 23:38:52
另一种方法是使用numpy matrix
class (而不是numpy数组)和I
属性。例如:
>>> m = np.matrix([[2,3],[4,5]])
>>> m.I
matrix([[-2.5, 1.5],
[ 2. , -1. ]])
发布于 2014-02-08 06:29:38
那inv呢?
例如: my_inverse_array = inv(my_array)
https://stackoverflow.com/questions/21638895
复制相似问题