# Create Table of replacement rules

I want to create a table of replacement rules.

g[a_, b_] := a -> b

t1 = Table[10 i + j, {i, 5}, {j, 3}]
t2 =  Table[ i + j, {i, 5}, {j, 3}]

g[  # & @@@ t1, # & @@@ t2 ]


The correct output is below:

{{11 -> 2, 12 -> 3, 13 -> 4},
{21 -> 3, 22 -> 4, 23 -> 5},
{31 -> 4, 32 -> 5, 33 -> 6},
{41 -> 5, 42 -> 6, 43 -> 7},
{51 -> 6, 52 -> 7, 53 -> 8}}


  {11, 21, 31, 41, 51} -> {2, 3, 4, 5, 6}


Which shows two concepts I am still trying to wrap my mind around how to accomplish in Mathematica.

In a 2-d list how to you select each row, and then perform an operation on each element of that row ( in this case take that element and make a rule replacment a -> b). Then iterate through every row.

• SetAttributes[g, Listable]
– Kuba
Commented May 1, 2014 at 20:02
• Moreover, # & @@@ t1 is effectively First /@ t1 so why do you expect all the values?
– Kuba
Commented May 1, 2014 at 20:14
• @Kuba I couldn't figure out how to get all the values. 2D lists in mathematica are still a challenge for me. Commented May 1, 2014 at 20:40

The shortest solution is to set attribute Listable for g:

SetAttributes[g, Listable]
g[a_, b_] := a -> b

t1 = Table[10 i + j, {i, 5}, {j, 3}];
t2 = Table[i + j, {i, 5}, {j, 3}];

g[t1, t2]

{{11 -> 2, 12 -> 3, 13 -> 4}, {21 -> 3, 22 -> 4, 23 -> 5},
{31 -> 4, 32 -> 5, 33 -> 6}, {41 -> 5, 42 -> 6, 43 -> 7},
{51 -> 6, 52 -> 7, 53 -> 8}}


Alternatively:

MapThread[Rule, {t1, t2}, 2]


Of course in this case it would be better if you could write a single Table expression:

t3 = Table[10 i + j -> i + j, {i, 5}, {j, 3}]

{{11 -> 2, 12 -> 3, 13 -> 4},
{21 -> 3, 22 -> 4, 23 -> 5},
{31 -> 4, 32 -> 5, 33 -> 6},
{41 -> 5, 42 -> 6, 43 -> 7},
{51 -> 6, 52 -> 7, 53 -> 8}}


If not you can use MapThread with a third parameter:

MapThread[g, {t1, t2}, 2] === t3

True


If none of the elements are themselves lists you can use the Listable property as Kuba showed. Otherwise MapThread is more general.

For completeness you could also write:

Thread /@ Thread[g[t1, t2]]