Given a list (e.g. of integers) x
and a list of 0
s and 1
s i
(of the same length as x
), how can I alter those entries of x
where the value of i
is 1?
For example, the code
n=10^8; x=RandomInteger[{-100,100},n]; i=RandomInteger[{0,1},n];
y=RandomInteger[{-100,100},n]; ByteCount@{x,i,y}
AbsoluteTiming@MaxMemoryUsed[i=Flatten[Position[i,1],1]]
AbsoluteTiming@MaxMemoryUsed[x[[i]]=y[[i]]]
shows that for 2.4GB of data, Position
spends 22sec and 10GB, whilst assignment spends only 0.85sec and 0.8GB. The former seems excessive. Is there a better way to do this? Python has this built-in (when i
is a numpy
array of booleans).
x = x (1 - i)
? $\endgroup$x[[Pick[Range@n,i,1]]=0
Code Wolfram like Wolfram, not Python, else it's Cobols all the way down... $\endgroup$x=x*(1-i)+y*i
. However, this only works ify
is of the same length asx
. But what if the length ofy
is the number of ones ini
and I want to dox[[i]]=y
? $\endgroup$