1
$\begingroup$

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 = {}
Do[
list = AppendTo[list,{a,b}],
{a,b,{{1,2},{3,4}}];

should give me

list

{{1,2},{3,4}}

I really need to loop over the variables.

$\endgroup$
  • 1
    $\begingroup$ Why not something like Table[g[a, b] /. Thread[{a, b} -> list], {list, {{1, 2}, {3, 4}}}]? $\endgroup$ – J. M.'s ennui Mar 30 '18 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 '18 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$ – J. M.'s ennui Mar 30 '18 at 11:59
  • $\begingroup$ @J.M. here is my code: dropbox.com/s/bfbfstrsbmorjvy/… $\endgroup$ – james Mar 30 '18 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$ – Henrik Schumacher Mar 30 '18 at 12:14
2
$\begingroup$
  1. Pass a list of parameter-tuples to Table
  2. Unpack the tuples into the variables you want

Example:

Table[
 Block[{a, b},
  {a, b} = pair;
  a^2 + b^2
 ], {pair, {{1, 2}, {3, 4}, {5, 6}}}
]
$\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.