Litwos
Litwos

Reputation: 1338

Add submatrices at certain locations

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: Test matrix design

Upvotes: 6

Views: 2934

Answers (2)

Mr Thomas Anderson
Mr Thomas Anderson

Reputation: 85

The inbuilt np.ix_ works perfectly

import numpy as np   
a=np.zeros([5,5])
b=np.random.rand(3,3)*100
idx=[0,2,3]
print(a)
a[np.ix_(idx, idx)]+=b
print(a)

the output is

[[0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]
[[56.22112929  0.         57.43572879  2.90797715  0.        ]
 [ 0.          0.          0.          0.          0.        ]
 [54.08128804  0.         23.53431307 24.03463619  0.        ]
 [96.7227866   0.          3.01937951 68.09775321  0.        ]
 [ 0.          0.          0.          0.          0.        ]]

Upvotes: 1

jfish003
jfish003

Reputation: 1332

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

Upvotes: 5

Related Questions