我正在处理的科学/工程应用程序有很多线性代数矩阵乘法,因此我使用 Numpy 矩阵。但是,python 中有许多函数可以互换地接受矩阵或数组类型。很好,不是吗?好吧,不是真的。让我用一个例子来说明这个问题:
from scipy.linalg import expm
from numpy import matrix
# Setup input variable as matrix
A = matrix([[ 0, -1.0, 0, 0],
[ 0, 0, 0, 1.0],
[ 0, 0, 0, 0],
[ 0, 0, 1.0, 0]])
# Do some computation with that input
B = expm(A)
b1 = B[0:2, 2:4]
b2 = B[2:4, 2:4].T
# Compute and Print the desired output
print "The innocent but wrong answer:"
print b2 * b1
print "The answer I should get:"
print matrix(b2) * matrix(b1)
运行时得到:
The innocent but wrong answer:
[[-0.16666667 -0.5 ]
[ 0. 1. ]]
The answer I should get, since I expected everything to still be matrices:
[[ 0.33333333 0.5 ]
[ 0.5 1. ]]
关于如何避免这种混淆的任何提示或建议?将变量包装在 matrix() 调用中以确保它们仍然是矩阵真的很麻烦。这方面似乎没有标准,因此可能导致难以检测的错误。
最佳答案
出于以下几个原因,我倾向于在 numpy
中使用 array
而不是 matrix
:
matrix
严格来说是二维的,而您可以拥有任意维度的numpy
array
。- 除了一些差异之外,
array
和matrix
操作非常相似interchangeable对于 Matlab 用户。 - 如果您始终使用
array
,那么您将使用numpy.dot()
(或者在 Python 3.5 中使用新的@
二元运算符)用于矩阵乘法。这将防止不确定*
在您的代码中实际做了什么的问题。当您遇到乘法错误时,您可以更轻松地发现问题,因为您确定要执行哪种乘法。
所以我建议您尝试坚持使用 numpy.array
,但也要记住 array
和 matrix
之间的区别。
最后,我发现在 bpython 上使用 numpy/scipy
是一种乐趣.自动提示可以帮助您以比不断查阅 numpy/scipy
文档更快的速度了解您尝试使用的函数的属性。
编辑:
array
与 matrix
之间的区别可能最好在这里回答:'array' or 'matrix'? Which should I use?
关于python - 混合 numpy 矩阵和数组的危险,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12024820/