Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Dynamic to monitor progress within functions

I am interested in monitoring the progress of a computation using Dynamic. This can be done interactively as follows:

In[3]:= Dynamic[iter]

In[4]:= Table[{iter, iter^2}, {iter, 1, 500000}];

However, if the Table is within a function such as

f[m_] := Module[{iter}, Table[{iter, iter^2}, {iter, 1, m}]]; 

how can I keep track of the value of iter, when I execute the function via

f[500000];

?

like image 278
asim Avatar asked Jan 07 '12 22:01

asim


1 Answers

Not sure it is a good advice, but:

f[m_] := 
Module[{iter}, getIter[] := iter; 
    Table[{iter, iter^2}, {iter, 1, m}]];

And then:

Dynamic[getIter[]]

f[500000];

EDIT

This will be better but somewhat more obscure:

ClearAll[f];
SetAttributes[f, HoldRest];
f[m_, monitorSymbol_: monitor] :=
   Block[{monitorSymbol},
     Module[{iter}, 
         monitorSymbol := iter; 
         Table[{iter, iter^2}, {iter, 1, m}]]
   ];

Here, you designate a certain symbol to monitor the state of your localized variable. By using Block, you ensure that your symbol does not obtain any global value at the end (more precisely, that its global value is not changed at the end - you may as well use a symbol that has some global value, if you so desire). The default symbol is monitor, but you can change it. Here is how you use it:

Dynamic[monitor]

f[500000];

This is a somewhat better suggestion than the first simpler one, since by using Block you guarantee that no global state modifications happen after the function finishes.

like image 58
Leonid Shifrin Avatar answered Sep 21 '22 12:09

Leonid Shifrin