0

I am running a For loop as follows:

table = {};
For[n = 0, n < 10, n++, {table = Append[table, n], Print[table]}]

I was wondering if there was a convenient way to replace the display of the print in previous rounds of the for loop so that only the print associated with the latest round of the loop is displayed.

FYI: I know what I'm running is insanely trivial. It's merely a simple representation of the more complicated calculations I'm running in a for loop. Each calculation takes some non-negligible time, hence why I want to see the display before it's finished the loop, but I don't want to see all the previous iterations.

Thanks in advance for any help.

Chris
  • 1,033
  • 4
  • 8

2 Answers2

1

I use PrintTemporary@Dynamic@ {Clock@Infinity, table};. Dynamic has low overhead and a low priority, so it generally does not slow loops down much. Beware if table get large, though. In that case I might use something like one of these:

PrintTemporary@Dynamic@ {Clock@Infinity, Length@table};
PrintTemporary@Dynamic@ {Clock@Infinity, Length@table, Last@table};

Examples:

table = {};
PrintTemporary@Dynamic@ {Clock@Infinity, table};
Do[ (* avoid For[] *)
 Pause[0.1]; (* for demonstration purposes only *)
 table = Append[table, n],
 {n, 0, 20}]
table (* if you wish to see the result *)

PrintTemporary@Dynamic@ {Clock@Infinity, n}; Table[ (* avoid Append[] ) Pause[0.1]; ( for demonstration purposes only ) n, ( if using Table[], can't see intermediate table *) {n, 0, 20}]

Or you can use Monitor for the Table[], as @Andreas suggests. I prefer including the Clock[Infinity].

Performance note: If your table is large and you cannot use Table instead of Append or it's inconvenient to do so, using table = {table, n} in the loop and table = Flatten[table] after the loop is more efficient. If the datum n is itself a List, then use table = \[FormalCapitalL][table, n] and table = List @@ Flatten[table]. (You can use in place of \[FormalCapitalL] whatever undefined symbol you prefer.)

References

Michael E2
  • 235,386
  • 17
  • 334
  • 747
0
table = {};
Monitor[For[n = 0, n < 10, n++, AppendTo[table, n]; Pause[1]], table]

The Pause is only to slow down the loop to better see the effect.

lericr
  • 27,668
  • 1
  • 18
  • 64