[英]Matrix element repetition bug
I'm trying to create a matrix that reads:我正在尝试创建一个矩阵,其内容如下:
[0,1,2]
[3,4,5]
[6,7,8]
However, my elements keep repeating.但是,我的元素不断重复。 How do I fix this?
我该如何解决?
import numpy as np
n = 3
X = np.empty(shape=[0, n])
for i in range(3):
for j in range(1,4):
for k in range(1,7):
X = np.append(X, [[(3*i) , ((3*j)-2), ((3*k)-1)]], axis=0)
print(X)
Results:结果:
[[ 0. 1. 2.]
[ 0. 1. 5.]
[ 0. 1. 8.]
[ 0. 1. 11.]
[ 0. 1. 14.]
[ 0. 1. 17.]
[ 0. 4. 2.]
[ 0. 4. 5.]
I'm not really sure how you think your code was supposed to work.我不确定您认为您的代码应该如何工作。 You are appending a row in
X
at each loop, so 3 * 3 * 7 times, so you end up with a matrix of 54 x 3.您在每个循环中在
X
中添加一行,因此 3 * 3 * 7 次,因此最终得到 54 x 3 的矩阵。
I think maybe you meant to do:我想也许你打算这样做:
for i in range(3):
X = np.append(X, [[3*i , 3*i+1, 3*i+2]], axis=0)
Just so you know, appending array is usually discouraged (just create a list of list, then make it a numpy array).正如您所知,通常不鼓励追加数组(只需创建一个列表列表,然后将其设为一个 numpy 数组)。
You could also do你也可以这样做
>> np.arange(9).reshape((3,3))
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.