我对选择NumPy数组的列感到有些困惑,因为结果与Matlab甚至NumPy矩阵不同 . 请参阅以下案例 .
在 Matlab 中,我们使用以下命令从矩阵中选择列向量 .
x = [0, 1; 2 3]
out = x(:, 1)
然后out变为 [0; 2]
,这是一个列向量 .
用 a NumPy Matrix 做同样的事情
x = np.matrix([[0, 1], [2, 3]])
out = x[:, 0]
然后输出是预期的 np.matrix([[0], [2]])
,它是一个列向量 .
但是,如果是 NumPy array
x = np.array([[0, 1], [2, 3]])
out = x[:, 0]
输出是 np.array([0, 2])
,它是1维,因此它不是列向量 . 我的期望是它应该是 np.array([[0], [2]])
. 我有两个问题 .
1. Why is the output from the NumPy array case different form the NumPy matrix case? This is causing a lot of confusion to me, but I think there might be some reason for this.
2. To get a column vector from a 2-Dim NumPy Array, then should I do additional things like expand_dims
x = np.array([[0, 1], [2, 3]])
out = np.expand_dims(x[:, 0], axis = 1)
1 回答
在MATLAB中,一切都至少有2个维度 . 在较旧的MATLAB中,2d是它,现在它们可以有更多 .
np.matrix
以旧的MATLAB为模型 .当您索引3d矩阵时,MATLAB会做什么?
np.array
更为一般 . 它可以有0,1,2或更多维度 .两者都选择一列或一行,并返回一个维度较少的数组 .
将返回具有单个维度的2d数组 .
在Octave(MATLAB克隆)中,索引会产生不一致的结果,具体取决于我选择的矩阵的哪一侧:
MATLAB / Octave最后增加了尺寸,显然也很容易将它们压在那边 .
numpy
在另一个方向上订购尺寸,并可根据需要在开始时添加尺寸 . 但是在索引时挤出单个维度是一致的 .事实上
numpy
可以有任意数量的维度,而MATLAB至少有2个是一个关键的区别,经常使MATLAB用户绊倒 . 但是,一个人的做法不仅仅是一般的原则,更多的是历史问题 .