4

I have two lists:

x = Range[1, 10, 1]
y = Range[2, 10, 2]

How can I produce a list consisting of the following elements (first element is the x value, second element the y value and third element some combination of it e.g. here the sum):

{
{x[[1]], y[[1]], x[[1]] + y[[1]]},
...
{x[[1]], y[[5]], x[[1]] + y[[5]]},
...
...
...
{x[[10]], y[[1]], x[[10]] + y[[1]]},
...
{x[[10]], y[[5]], x[[10]] + y[[5]]}
}

=

{
{1,2,3},
...
{1,10,11},
...
...
...
{10,2,12},
...
{10,10,20}
}
lio
  • 2,396
  • 13
  • 26

4 Answers4

12

A more Mathematica-ish/functional approach than Do is as follows:

x = Range[1, 10, 1];
y = Range[2, 10, 2];
Flatten[Outer[{#1, #2, #1 + #2} &, x, y], 1]
evanb
  • 6,026
  • 18
  • 30
5

Matrix multiplication is another option:

Tuples[{x, y}].{{1, 0, 1}, {0, 1, 1}}
Coolwater
  • 20,257
  • 3
  • 35
  • 64
4

As in the comments remarked, you can use Table as follows

x = Range[1, 10, 1];
y = Range[2, 10, 2];
t1 = Flatten[
  Table[{x[[i]], y[[j]], x[[i]] + y[[j]]}, {i, Length@x}, {j, Length@y}]
  ,1]

{{1, 2, 3}, {1, 4, 5}, {1, 6, 7}, {1, 8, 9}, {1, 10, 11}, {2, 2,
4}, {2, 4, 6}, {2, 6, 8}, {2, 8, 10}, {2, 10, 12}, {3, 2, 5}, {3, 4,
7}, {3, 6, 9}, {3, 8, 11}, {3, 10, 13}, {4, 2, 6}, {4, 4, 8}, {4,
6, 10}, {4, 8, 12}, {4, 10, 14}, {5, 2, 7}, {5, 4, 9}, {5, 6, 11}, {5, 8, 13}, {5, 10, 15}, {6, 2, 8}, {6, 4, 10}, {6, 6, 12}, {6, 8, 14}, {6, 10, 16}, {7, 2, 9}, {7, 4, 11}, {7, 6, 13}, {7, 8, 15}, {7, 10, 17}, {8, 2, 10}, {8, 4, 12}, {8, 6, 14}, {8, 8, 16}, {8, 10, 18}, {9, 2, 11}, {9, 4, 13}, {9, 6, 15}, {9, 8, 17}, {9, 10, 19}, {10, 2, 12}, {10, 4, 14}, {10, 6, 16}, {10, 8, 18}, {10, 10, 20}}

or, for example, a Do loop

t2 = {};
Do[
 AppendTo[t2, {x[[i]], y[[j]], x[[i]] + y[[j]]}]
 , {i, Length@x}
 , {j, Length@y}
 ]
t2 == t1

True

There are surely a lot of possibilities to do this.

Mauricio Fernández
  • 5,463
  • 21
  • 45
3

Also

{##, Plus@##} & @@@ Tuples[{x, y}]

Or

Distribute[{x, y}, List, List, List, {##, Plus@##} &]

Mathematica graphics

kglr
  • 394,356
  • 18
  • 477
  • 896