5
$\begingroup$

I would like to assign values for the two indexes at the same time. For example:

Table[x + y, {x, {1, 2, 3}}, {y, {1, 2, 3}}]

will give me an output of:

{{2, 3, 4}, {3, 4, 5}, {4, 5, 6}}

I'd like to have an output using {{x,y} = {{1,1},{2,2},{3,3}} to produce

{2,4,6}

How can I do this?

$\endgroup$
3
  • 2
    $\begingroup$ Plus @@@ {{1, 1}, {2, 2}, {3, 3}} $\endgroup$
    – Bob Hanlon
    Nov 8 '21 at 2:10
  • 1
    $\begingroup$ Total /@ {{1, 1}, {2, 2}, {3, 3}} $\endgroup$
    – Syed
    Nov 8 '21 at 7:13
  • $\begingroup$ Also Total[lst,{2}]] $\endgroup$
    – user1066
    Nov 8 '21 at 9:39
6
$\begingroup$

In this case you must use a single iterator variable in Table, but you can "unpack" its value into multiple variables later.

Table[
  Block[{x, y}, 
    {x, y} = i; 
    x + y
  ], 
  {i, {{1, 2}, {2, 3}, {3, 4}}}
]

Instead of unpacking, you can also insert the values into the argument of a function directly,

Table[Plus @@ i, {i, {{1, 2}, {2, 3}, {3, 4}}}]
(* {3, 5, 7} *)

Table[(#1 + 2 #2 &) @@ i, {i, {{1, 2}, {2, 3}, {3, 4}}}]
(* {5, 8, 11} *)
$\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.