问题描述
我编写了以下代码,该代码可以做到:(1)生成形状为(3, 16)
的根矩阵,以及(2)生成1000个二元向量C
,以便每个向量在根矩阵的末尾迭代地添加一个一个时间.
I wrote the following code that does: (1) Generate root matrix of shape (3, 16)
, and (2) Generate 1000 binary vectors C
such that each vector is added at the end of the root matrix iteratively one at a time.
代码如下(python 2.7):
The code is the following (python 2.7):
# STEP1: Generate root matrix
root = [random.randint(0, 2 ** 16 - 1) for _ in range(16 - 1)]
root = [('{0:0' + str(16) + 'b}').format(x) for x in root]
root = np.asarray([list(map(int, list(x))) for x in root], dtype=np.uint8)
# STEP2: Generate 1000 binary vectors
C = [random.randint(0, 2 ** 16 - 1) for _ in range(1000)]
C = list(set(C))
C = [('{0:0' + str(16) + 'b}').format(x) for x in C]
C = np.asarray([list(map(int, list(x))) for x in C], dtype=np.uint8)
# Step3: For each vector of C, append it at the end of root matrix
for i in range(1000):
batch = root[i:(i + (len(root)))]
batch = np.append(batch, C[i])
print(batch)
# Continue to process batch after being extended by adding a new vector
矩阵C
看起来像这样:
[[0 1 1 ..., 0 1 1]
[1 0 1 ..., 1 0 1]
[0 1 0 ..., 1 1 0]
...,
[1 1 0 ..., 1 0 0]
[0 0 1 ..., 1 1 0]
[1 1 1 ..., 1 1 1]]
问题是np.append(batch, C[i])
将所有向量合并为一个向量,但这不是我想要的.我的目标是通过迭代添加向量C[i]
将root
矩阵从(3, 16)
扩展为(4,16)
.我该如何实现?
The problem is that np.append(batch, C[i])
merges all vectors into a single one but this is not what I want. My goal is to extend the root
matrix from (3, 16)
to be (4,16)
by just adding a vector C[i]
iteratively. How can I achieve that?
谢谢
推荐答案
如果您可以交换以下内容:
If you can swap this:
batch = root[i:(i + (len(root)))]
batch = np.append(batch, C[i])
为此:
batch = np.append(batch, [C[i]], axis=0)
axis
允许您在特定维度上附加两个矩阵.因此,我们将C[i]
制成矩阵并将其附加到维度0中.
axis
allows you to append two matrices on a particular dimension. So we make C[i]
into a matrix and append it in dimension 0.
我不确定此batch = root[i:(i + (len(root)))]
的意图是什么,但每次都会将batch
缩短为一个根大小的矩阵,因此它不会增大大小.实际上,随着您在root
末尾附近收缩.
I am not sure what the intention of this batch = root[i:(i + (len(root)))]
is but it shortens batch
to a matrix the size of root every time so it will not increase in size. It actually shrinks as you near the end of root
.
C也不总是1000个向量.使其具有唯一性会删除一些内容.
Also C is not always 1000 vectors. Making them unique removes some.
这篇关于通过添加额外的列表扩展类似矩阵的numpy数组时出现的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!