Issue
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.
Solution
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
Answered By - jfish003
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.