3
$\begingroup$

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

Instead I am getting:

  {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.

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

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]
$\endgroup$
5
$\begingroup$

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]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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