首页 > 解决方案 > 循环直到矩阵满?

问题描述

我有一个条件语句,它将矩阵 A 中的二进制值行添加到矩阵 B。我想把它放在一个循环中,以便它继续从矩阵 A 中添加行,直到矩阵 B 已满。目前,矩阵 B 被初始化为 10 x 10 的零矩阵。我是否需要以不同的方式初始化矩阵 B 才能创建此条件,还是有办法按原样进行?

下面大致是我的代码到目前为止的样子

from random import sample
import numpy as np

matrixA = np.random.randint(2, size=(10,10))

matrixB = np.zeros((10,10))

x, y = sample(range(1, 10), k=2)

if someCondition:
    matrixB = np.append(matrixB, [matrixA[x]], axis=0)
else:
    matrixB = np.append(matrixB, [matrixA[y]], axis=0)

标签: matrix

解决方案


你不需要一个循环。使用智能索引真的很容易做到这一点。例如:

import numpy as np

A = np.random.randint(0, 10, size=(20,10))
B = np.empty((10, 10))
print(A)
# Copy till the row that satisfies your conditions. Here I assume it to be 10
B = A[:10, :]
print(B)

推荐阅读