4
$\begingroup$

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}
}
$\endgroup$
  • $\begingroup$ Take a look at Table and may be Flatten afterwards $\endgroup$ – Mauricio Fernández Nov 23 '16 at 13:41
  • $\begingroup$ Is this the only possibility? $\endgroup$ – lio Nov 23 '16 at 13:43
  • 1
    $\begingroup$ No, you can also create first an empty list and fill it with AppendTo within a Do loop. Try it out :D $\endgroup$ – Mauricio Fernández Nov 23 '16 at 13:45
12
$\begingroup$

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

Matrix multiplication is another option:

Tuples[{x, y}].{{1, 0, 1}, {0, 1, 1}}
$\endgroup$
4
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ Thank you. Is instead of using loops also a solution with Map or ReplaceList possible? $\endgroup$ – lio Nov 23 '16 at 13:51
  • 3
    $\begingroup$ performance tunning: point 3.2 $\endgroup$ – Kuba Nov 23 '16 at 13:55
  • $\begingroup$ Cool info! Thanks! $\endgroup$ – Mauricio Fernández Nov 23 '16 at 13:57
3
$\begingroup$

Also

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

Or

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

Mathematica graphics

$\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.