我正在处理从MatLab到Python的代码移植,我一直在努力使用Numpy切片重现这部分代码所做的事情,因为它允许负索引:
A_new = [A(:, 1:i-1) v1 v2 A(:, i+1:size(A,2))];
让我们来看看几个案例:
i = 1;
A = [1; 1; 1; 1; 1];
v1 = [1; 1; 0; 0; 0];
v2 = [0; 0; 1; 1; 1];
A(:, 1:i-1) % column slicer is 1:i-1 which is 1:0 and therefore returns empty
Empty matrix: 5-by-0
A(:, i+1:size(A,2)) % column slicer is i+1:size(A,2) which is 2:1 and therefore returns empty
Empty matrix: 5-by-0
[A(:, 1:i-1) v1 v2 A(:, i+1:size(A,2))] % the result is just v1 and v2 stacked:
1 0
1 0
0 1
0 1
0 1
i = 1;
A = [1 0; 1 0; 0 1; 0 1; 0 1];
v1 = [0; 1; 0; 0; 0];
v2 = [1; 0; 0; 0; 0];
A(:, 1:i-1) % column slicer is 1:i-1 which is 1:0 and therefore returns empty
Empty matrix: 5-by-0
A(:, i+1:size(A,2)) % column slicer is i+1:size(A,2) which is 2:2 and therefore returns
0
0
1
1
1
[A(:, 1:i-1) v1 v2 A(:, i+1:size(A,2))] % the result is v1, v2 and last column of A stacked:
0 1 0
1 0 0
0 0 1
0 0 1
0 0 1
我并不认为它是正确的,而且可能有更好的方法来实现相同的结果,但以下是我在Python中复制它的方式:
z, k = A.shape
ls = np.zeros((z, 0), dtype=float) if i - 1 < 0 else A[:, 0:(i - 1)]
rs = np.zeros((z, 0), dtype=float) if k < i + 1 else A[:, (i + 1):k]
a_new = np.hstack((ls, v1, v2, rs))
第一个案例的效果与预期一致。第二个失败了:
i = 0
A = np.asarray([[1., 0.], [1., 0.], [0., 1.], [0., 1.], [0., 1.]])
v1 = np.asarray([[0., 1., 0., 0., 0.]]).T
v2 = np.asarray([[1., 0., 0., 0., 0.]]).T
# LS: i - 1 < 0 | 0 - 1 < 0 | -1 < 0 ... LS is correctly evaluated as np.zeros((z, 0), dtype=float)
# RS: k < i + 1 | 1 < 0 + 1 | 1 < 1 ... therefore RS is evaluated as A[:, (i + 1):k]
# This should translate into A[:, 1:1] and take the last column of A, but instead it returns an empty ndarray with the following error:
File "...\lib\site-packages\numpy\core\_methods.py", line 44, in _amin
return umr_minimum(a, axis, None, out, keepdims, initial, where)
ValueError: zero-size array to reduction operation minimum which has no identity
2条答案
按热度按时间qf9go6mv1#
在您的代码中,首先:
我认为这是:
因为您没有在代码python中定义变量
a
。现在,我们检查一下python代码
a_new = np.hstack((ls, v1, v2, rs))
中变量的形状:输出结果:
所以我们知道问题是在调用函数
np.hstack
时维度不一致,只需在定义这两个变量时通过调换向量来调整v1, v2
的维度:然后我们得到了:
qkf9rpyu2#
如果
A
为(5,1),则此索引生成两个(5,0)数组:对于a(5,2),结果是a(5,0)和(5,1)
要完全测试这一点,我需要启动
Octave
,并尝试其他一些A
形状和其他i
。