My goal is to replace the zeros of one list with the (i-1)th element of a second list. For example, if
list1 = {0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0}
and
list2 = {6, 1, 4, 7, 2, 9, 10, 8, 11, 3, 5, 0, 12}
the desired output is {0, 1, 1, 4, 7, 1, 1, 10, 1, 11, 3, 1, 0}. Note that the first element of the output is defined as 0 still.
My attempt to create a code for this is to first find the zeros of list1
then run a for-loop for $i \in$zeroslist1
.
zeroslist1 = Flatten[Position[list1, 0]]
DeleteCases[
Flatten[Reap@
Do[Sow[ReplacePart[vtest1,
i -> vtest2[[i - 1]] & /@ zeroslist1]], {i, zeroslist1}], 2], Null]
The results of the output are:
{{List,1,1,0,0,1,1,0,1,0,0,1,0}, {0,1,1,4,0,1,1,0,1,0,0,1,0}, {0,1,1,0,7,1,1,0,1,0,0,1,0},{0,1,1,0,0,1,1,10,1,0,0,1,0}, {0,1,1,0,0,1,1,0,1,11,0,1,0},{0,1,1,0,0,1,1,0,1,0,3,1,0}, {0,1,1,0,0,1,1,0,1,0,0,1,0}}.
Either a cleaner way to code the desire output or a method of merging the output of my current for-loop to get the desired output would be great.