# Updating a nested list using elements from another nested list of the same shape

I am new to Mathematica. A quick question:

Given

a = {{1,0,0,2},{2,0,1,0}}
aR = {{1,0,1,0},{0,1,0,1}}


if element in a is 0, I would like to replace this element with the element from aR in the same position, so results should be 

{{1, 0, 1, 2}, {2, 1, 1, 1}}.

I tried this but does not work

(a[[#1, #2]] = If [a[[#1, #2]] == 0, aR[[#2, #1]], a[[#1, #2]]]) & @@@
{Range[Part[Dimensions[a], 1]], Range[Part[Dimensions[a], 2]]};


• a + (1 - Unitize@a)*aR... and perhaps more understandable ReplacePart[a, {x_, y_} /; a[[x, y]] == 0 :> aR[[x, y]]] or MapThread[If[# == 0, #2, #] &, {a, aR}, 2]
– ciao
Jun 10, 2016 at 21:54
• MapIndexed[If[#1 == 0, Extract[aR, #2], #1] &, a, {2}] Jun 11, 2016 at 8:25

ciao doesn't like to write answers, so I will do it as a CW.

a + (1 - Unitize@a)*aR


Perhaps more understandable:

ReplacePart[a, {x_, y_} /; a[[x, y]] == 0 :> aR[[x, y]]]


or

MapThread[If[# == 0, #2, #] &, {a, aR}, 2]


All give

{{1, 0, 1, 2}, {2, 1, 1, 1}}

• Just a note: the first method is about 50 times faster on bigger datasets Jun 10, 2016 at 22:39
• @BlacKow - a1 + BitXor[1, Unitize@a1]*a2 s/b a bit faster yet...
– ciao
Jun 10, 2016 at 23:11
• @ciao, well, when you put it that way: {{1, 0, 0, 2}, {2, 0, 1, 0}} ~BitOr~ {{1, 0, 1, 0}, {0, 1, 0, 1}}`. (Of course, this assumes the entries in the two matrices are all nonnegative integers.) Jun 10, 2016 at 23:18
• @J.M.--- might want to rethink that ;=}
– ciao
Jun 10, 2016 at 23:51