Can I create a Do loop where instead of varying only 1 variable, I vary multiple sets of variable ?

For example (the syntax is invented and only serves as a purpose to show what I mean):

list = {}
list = AppendTo[list,{a,b}],

should give me



I really need to loop over the variables.

  • 1
    $\begingroup$ Why not something like Table[g[a, b] /. Thread[{a, b} -> list], {list, {{1, 2}, {3, 4}}}]? $\endgroup$ Mar 30, 2018 at 11:52
  • $\begingroup$ @J.M. Thank you for your comment. I cannot use such structure because the variables are parameters inside a large function. In each loop I want to update specific parameters to specific values, while keeping other parameters the same. $\endgroup$
    – james
    Mar 30, 2018 at 11:55
  • 3
    $\begingroup$ Based on this and your other question, I have the nagging suspicion that you've chosen an architecture that is making simple substitutions and looping more complicated than it has to be. $\endgroup$ Mar 30, 2018 at 11:59
  • $\begingroup$ @J.M. here is my code: dropbox.com/s/bfbfstrsbmorjvy/… $\endgroup$
    – james
    Mar 30, 2018 at 12:08
  • 1
    $\begingroup$ What about list = {};Do[list = AppendTo[list,x],{x,{{1,2},{3,4}}];? Note however that using Append in loops will slow things down considerably as it involves a lot of copy operations. Solutions based on Sow and Reap (or even better: Internal`Bag) should yield better performance. $\endgroup$ Mar 30, 2018 at 12:14

1 Answer 1

  1. Pass a list of parameter-tuples to Table
  2. Unpack the tuples into the variables you want


 Block[{a, b},
  {a, b} = pair;
  a^2 + b^2
 ], {pair, {{1, 2}, {3, 4}, {5, 6}}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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