Say I'm running some process of unknown duration, and during the process, I need to periodically record the state of some variable. If we knew exactly how long the process took, we could simply specify an array of appropriate size, and know that when the array is filled, we'll be finished. However, if this is not the case, it seems one has to resort to operations like:
testArray = Append[testArray,dataPoint];
Which becomes both computationally intensive and memory intensive at the limit of large array sizes. Is there a better way to proceed? Or should I simply specify a very large version of testArray
and then chop it down after I've finished my procedure and filled it to some limited extent?
Let me provide an example of the kind of process I'm thinking of (using the horrible Append
strategy just to make things clear):
randVar=0;
storage={};
While[randVar<=0.99,
randVar=RandomReal[];
storage = Append[storage,randVar];
];
Length[storage];
How do we use e.g. Sow/Reap to deal with the array updates?
myList={}
, then at each update domyList={update,myList}
. You can flatten/manipulate as needed to collect to final result. Or, useSow
andReap
. $\endgroup$Sow/Reap
, but not a huge difference. For your question,Sow/Reap
makes the most sense. As far as the second query, whenever possible, do list operations as one, so one flatten will beat repeated. $\endgroup$