3
$\begingroup$

I am trying to get a loop structure using While to repeatedly evaluate another cell referred to in its body (using a cell tag).

"this is the while construct";
x = 2;
y = 5;
While[x < y,
  NotebookLocate["code"];
  FrontEndTokenExecute["EvaluateCells"];
  x
  y
]

and this is the cell called "code"

"this cell contains the code i want to run";
x = x + 0.1;
y = y - 0.1;

My code seems to enter an endless loop.

What I expected was when the two numbers, x and y, became equal, the loop would stop. What am I doing wrong?

$\endgroup$
2
  • $\begingroup$ in actuality, what i am trying to do is, run an external notebook from the while $\endgroup$
    – yoav matia
    Aug 4, 2013 at 14:22
  • $\begingroup$ for example: lets say you have a very elaborate code calculating a very complex physics problem. and you want to run it iteratively until its parameters converge. i need an elegant and readable code... main.nb contains the while loop, and physics.nb will contain a single iterative run. how do i do this? $\endgroup$
    – yoav matia
    Aug 4, 2013 at 14:35

2 Answers 2

3
$\begingroup$

Here is an example for now. Notice that in the process[] function, if you intend to modify the input arguments, you have to make a temporary copy of them, since default passing in Mathematica is by value.

(*---- This function is the main driver ---*)
main[] := Module[{x = 2, y = 5},
   While[x < y,
    {x, y} = process[x, y];
    Print["x=", x, "y=", y];
    ]
   ];

(*---- my processing function called from a loop from somewhere *)
process[x0_, y0_] := 
 Module[{x = x0, y = y0},(*to allow us to modify input*)
  (*assume we are using x and y much more here *)

  x = x + 0.1;
  y = y - 0.1;

  (*we are done, let return the result*)
  {x, y}
  ]

Mathematica graphics

$\endgroup$
2
  • $\begingroup$ i just got back from abroad... i will run this now, give me some time $\endgroup$
    – yoav matia
    Aug 24, 2013 at 7:18
  • $\begingroup$ Nassers solution is spot on!!! Thank you very much Nasser, you idea worked perfectly. if you ever have problems with fluid dynamics or heat transfer just say the word, i will be happy to return a favor :) $\endgroup$
    – yoav matia
    Aug 24, 2013 at 7:32
3
$\begingroup$

Try this:

x = 2;
y = 5;

Monitor[
 While[x < y,
  NotebookEvaluate["code.nb"]
  ],
 {x, y}
 ]

Monitor is optional. I used it to make sure that something was happening. :)

$\endgroup$

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.