I am trying to change a block within a two-dimensional numpy array by inserting pasting another 2-dim array. The sample below gives me unexpected behavior:
import numpy as np
M=np.ones((4,4))
print(M)
S=[0,1]
print('to be set to zero: ',M[S,:][:,S])
M[S,:][:,S]=np.zeros((2,2))
print('after setting to zero: ',M)
I would expect the upper left corner of M to become zeros. However I get
[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]
to be set to zero: [[ 1. 1.]
[ 1. 1.]]
after setting to zero: [[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]
It seems that I can extract the upper left block but not write to it. I get the expected behavior if I replace the line
M[S,:][:,S]=np.zeros((2,2))
with
M[0:2,:][:,0:2]=np.zeros((2,2))
What am I doing wrong? Thank you
M[S,:]creates a copy;M[0:2,:]a view.