Add submatrices at certain locations

被刻印的时光 ゝ 提交于 2021-01-27 15:01:14

问题


I have a test matrix (z) of shape 40x40, filled with zeros.

I need to add 4 submatrices of shapes, called c1, c2(5x5), c3(7x7) and c4(9x9) at specific locations to the test matrix.

I want to place the submatrices centers at the respective locations, then simply perform addition of elements. The locations in the test matrix are: z(9,9), z(9,29), z(29,9), z(29,29).

I tried looking at these threads, but I cannot get a clear answer on how resolve my problem. How to add different arrays from the center point of an array in Python/NumPy Adding different sized/shaped displaced NumPy matrices

Code examples I tried:

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

But this only adds the centers, not the entire submatrix.

It should look like this:


回答1:


The nice thing about array slicing in numpy is you don't need the for loops that you are using. Also the reason that it is only putting the center element is because you only put a single element there (c1[c1mid,c1mid] is a single number) here is what you could do:

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


来源:https://stackoverflow.com/questions/32666520/add-submatrices-at-certain-locations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!