I have an vector, x (a numpy array), and I want to create two copies of this; one (y) where the even points are set to zero and one, z, where the odd points are set to zero. I have come up with two possible ways of doing this.
1)
x = numpy.array([1,2,3,4,5,6,7,8,9,10])
y = x
y[::2] = 0
Result
x
array([ 0, 2, 0, 4, 0, 6, 0, 8, 0, 10])
y
array([ 0, 2, 0, 4, 0, 6, 0, 8, 0, 10])
z = x
z[:,1::2] = 0
Result:
x
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
z
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Or:
2)
y = numpy.zeros(10)
y[::2] = x[::2]
Result:
y
array([ 1., 0., 3., 0., 5., 0., 7., 0., 9., 0.])
x
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
z = numpy.zeros(10)
z[1::2] = x[1::2]
Result:
z
array([ 0., 2., 0., 4., 0., 6., 0., 8., 0., 10.])
x
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
The first method seems to have x coupled to y and z so that any changes to y or z affect x too. The second seems a less-intuitive way of writing this but gives the intended results. Why do these two methods give different results? The first in particular seems rather dangerous in terms of keeping track of what is happening in your code!