Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
in actuality, what i am trying to do is, run an external notebook from the while –  yoav matia Aug 4 '13 at 14:22
    
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? –  yoav matia Aug 4 '13 at 14:35
add comment

2 Answers 2

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

share|improve this answer
    
i just got back from abroad... i will run this now, give me some time –  yoav matia Aug 24 '13 at 7:18
    
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 :) –  yoav matia Aug 24 '13 at 7:32
add comment

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. :)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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