0
$\begingroup$

Consider the following simple loop:

n=0;
Do[n++;Print[n],{10}]

Mathematica writes:

1

2

3

...

I want mathematica to write dynamically the value of the variable n. I mean I want Mathematica to write 1, cancel it and write 2, cancel it and write 3 and so on.

Is it possible?

$\endgroup$
  • 1
    $\begingroup$ Try n=0;Dynamic[n] and then (in a new line) Do[n++;,{100000000}]. $\endgroup$ – Henrik Schumacher Aug 31 '18 at 15:42
3
$\begingroup$

You can use Monitor

Monitor[Do[n++; Pause[.5], {10}], n]

Monitor can increase the time of a calculation. Use Refresh to control the update interval used for displaying:

 Monitor[Do[i, {i, 10^7}],
 Refresh[Pause[0.03] i, UpdateInterval -> 0.2, TrackedSymbols -> {}]]

Or as Henrik said in the comment Dynamic:

Do[n++; Pause[.5], {10}]
Dynamic[n]

But Dynamic is purely frontend function. Monitor is convinient for computation, for example for long running remote monitoring:

Monitor[Do[n++;, {3}], 
 SendMail["test@test.com", "n = " <> ToString[n]]]

BTW take a look at Echo too, might come handy, while not this case.

| improve this answer | |
$\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.