2
$\begingroup$

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]]};

Could you please help me?

$\endgroup$
2
  • 2
    $\begingroup$ 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] $\endgroup$
    – ciao
    Jun 10, 2016 at 21:54
  • $\begingroup$ MapIndexed[If[#1 == 0, Extract[aR, #2], #1] &, a, {2}] $\endgroup$
    – andre314
    Jun 11, 2016 at 8:25

1 Answer 1

6
$\begingroup$

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}}

$\endgroup$
4
  • $\begingroup$ Just a note: the first method is about 50 times faster on bigger datasets $\endgroup$
    – BlacKow
    Jun 10, 2016 at 22:39
  • 2
    $\begingroup$ @BlacKow - a1 + BitXor[1, Unitize@a1]*a2 s/b a bit faster yet... $\endgroup$
    – ciao
    Jun 10, 2016 at 23:11
  • 1
    $\begingroup$ @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.) $\endgroup$ Jun 10, 2016 at 23:18
  • $\begingroup$ @J.M.--- might want to rethink that ;=} $\endgroup$
    – ciao
    Jun 10, 2016 at 23:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.