【问题标题】:Add submatrices at certain locations在某些位置添加子矩阵
【发布时间】:2015-12-16 11:01:00
【问题描述】:

我有一个 40x40 形状的测试矩阵 (z),用零填充。

我需要在测试矩阵的特定位置添加 4 个形状子矩阵,称为 c1、c2(5x5)、c3(7x7) 和 c4(9x9)。

我想将子矩阵中心放置在各个位置,然后简单地执行元素的添加。 测试矩阵中的位置是: z(9,9), z(9,29), z(29,9), z(29,29)。

我尝试查看这些线程,但我无法明确回答如何解决我的问题。 How to add different arrays from the center point of an array in Python/NumPy Adding different sized/shaped displaced NumPy matrices

我试过的代码示例:

def zero_matrix(d):
    matrix = np.zeros((d,d), dtype=np.float)
    return matrix

z = zero_matrix(40)

c1 = np.genfromtxt('xxxxxx', dtype=None, delimiter = '\t')
c2 = np.genfromtxt('xxxxxx', dtype=None, delimiter = '\t')
c3 = np.genfromtxt('xxxxxx', dtype=None, delimiter = '\t')
c4 = np.genfromtxt('xxxxxx', dtype=None, delimiter = '\t')


def adding(z):
    for i in range(z.shape[0]):
        for j in range(z.shape[1]):
            if i == 9 and j==9:
                c1mid = c1.shape[0]//2
                z[i,j] = c1[c1mid,c1mid]
    print z
    return z

但这只会添加中心,而不是整个子矩阵。

它应该看起来像这样:

【问题讨论】:

    标签: python numpy matrix


    【解决方案1】:

    numpy 中数组切片的好处是你不需要你正在使用的 for 循环。另外它只放置中心元素的原因是因为你只放了一个元素(c1[c1mid,c1mid] 是一个数字)你可以这样做:

        z[7:12,7:12] = c1
        z[7:12,27:32] = c2
        z[26:33,6:14] = c3
        z[25:34,25:33] = c4
    

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 1970-01-01
      • 2018-06-25
      • 2018-06-28
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      相关资源
      最近更新 更多