Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I often use Tables inside of Tables to fill 2 dimensional arrays.

Is it possible for the lower example code to substitute the Table environments by a more sophisticated and shorter code?

list1 = Range[1, 10]; 
list2 = Range[11, 20]; 

n1 = Length[list1]; 
n2 = Length[list2]; 

result = Array[0 &, {n1, n2}]; 

Table[
  Table[
    result[[c1, c2]] = list1[[c1]] + list2[[c2]], 
    {c1, 1, n1}
  ], 
  {c2, 1, n2}
]
share|improve this question
3  
list2 + # & /@ list1? – Kuba Feb 27 at 20:54
    
great ... thank you. This is what I was looking for. Probably that can be extended for more than two Table loops: for 3 Tables list3 + # & /@ list2 + # & /@ list1. Is that correct? – mrz Feb 27 at 21:07
up vote 8 down vote accepted
Outer[Plus, Range[1, 10], Range[11, 20]]
share|improve this answer
    
This is awesome ... I vote for this. – mrz Feb 27 at 21:27

Using your current variables, you can substitute both of your tables with just one table by using the code below:

list1 = Range[1, 10]; 
list2 = Range[11, 20]; 

n1 = Length[list1]; 
n2 = Length[list2];

result = Array[0 &, {n1, n2}];

Table[result[[c1, c2]] = list1[[c1]] + list2[[c2]], {c1, 1, n1}, {c2, 1, n2}]

The reason that this is possible is that Table can actually take in multiple arguments for loops and will treat it like you did using multiple Tables.

I hope this helped to answer your question.

EDIT: I would comment, except I don't have enough points yet, but John Doty's answer is much better.

share|improve this answer
    
this makes the code much shorter, when even more Tables are present ... thanks – mrz Feb 27 at 21:10
    
yay, glad I was able to help. – nbingo Feb 29 at 6:37
Partition[#, 10, 1] & @ Range[12, 30]

{{12, 13, 14, 15, 16, 17, 18, 19, 20, 21}, {13, 14, 15, 16, 17, 18, 19, 20, 21, 22}, {14, 15, 16, 17, 18, 19, 20, 21, 22, 23}, {15, 16, 17, 18, 19, 20, 21, 22, 23, 24}, {16, 17, 18, 19, 20, 21, 22, 23, 24, 25}, {17, 18, 19, 20, 21, 22, 23, 24, 25, 26}, {18, 19, 20, 21, 22, 23, 24, 25, 26, 27}, {19, 20, 21, 22, 23, 24, 25, 26, 27, 28}, {20, 21, 22, 23, 24, 25, 26, 27, 28, 29}, {21, 22, 23, 24, 25, 26, 27, 28, 29, 30}}

Partition[#, 10, 1] &@Range[12, 30] == 
Table[Table[result[[c1, c2]] = list1[[c1]] + list2[[c2]], {c1, 1, n1}], {c2, 1,n2}]

True

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.