Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
    
SetAttributes[g, Listable] –  Kuba May 1 at 20:02
    
Moreover, # & @@@ t1 is effectively First /@ t1 so why do you expect all the values? –  Kuba May 1 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. –  olliepower May 1 at 20:40

2 Answers 2

up vote 4 down vote accepted

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]
share|improve this answer

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]]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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