I am running While loops in an initialization cell for the purpose of submitting the notebook to the online cluster. However it appears to me that the While loop in an initialization cell would run twice. For example, if one evaluates

n = 1; While[n < 1000, Print[n]; n++]

in an initialization cell, mathematica will run twice and delete the first output. Could anyone tell me how to fix this? Thanks!


1 Answer 1


Mathematica won't run it twice unless you (possibly unknowingly) instruct it to do so.

I suspect this is what is happening (please update the question with the details):

You put some initialization cells in a notebook. You saved the notebook, closed it an reopened it (or alternatively you quit the kernel). Then you used the Evaluation -> Evaluate Notebook menu option. This queues all cells in the notebook for evaluation, whether they are initialization cells or not.

At this point a dialog box appears asking if you want to evaluate initialization cells first.

enter image description here

If you answer yes, the initialization cells will get evaluated immediately, then Mathematica continutes with the evaluation queue. But the queue already contained the initialization cells, so these get evaluated a second time as well.

Either this or something very similar may be happening on your system. It is impossible to tell without a full description of what you are doing.

You can always just answer "No" at that prompt to prevent this.

If you convert the notebook to an .m file and run that in command line mode, as I expect you will do on the cluster, then this is not an issue. There are no longer any cells, and the front end is not involved. The commands in the .m file will just get evaluated sequentially.

  • $\begingroup$ Thank you that's exactly what I was asking! $\endgroup$ Commented Feb 2, 2016 at 20:00

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.