# Numerical simulation - getting slower the more data I have [closed]

I'm simulating the trajectory of a charged particle. I have the coordinates saved in the list $coor$ ({{0,0,0},{0.1,0.1,0.003}, etc}) as the time goes on this array is getting bigger and the computation slower. What is the usual way to solve this issue?

I guess that using

coor=Append[coor,r]


is't the best way to save data on the way. Do you have any sugesstions? Thanks

-

## closed as off-topic by Michael E2, ciao, gpap, Oleksandr R., ÖskåJun 9 '14 at 10:22

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "This question cannot be answered without additional information. Questions on problems in code must describe the specific problem and include valid code to reproduce it. Any data used for programming examples should be embedded in the question or code to generate the (fake) data must be included." – Michael E2, ciao, gpap, Oleksandr R., Öskå
If this question can be reworded to fit the rules in the help center, please edit the question.

Maybe Reap and Sow？ –  Apple Jun 8 '14 at 11:32
–  Yves Klett Jun 8 '14 at 11:46
Perhaps NDSolve, Table, NestWhileList etc. There is not enough information to give a definitive answer. –  Michael E2 Jun 9 '14 at 2:12

Define a list large enough to hold your coordinates:

coor = Table[Null, {100}];


Then, starting with

i = 1;


Let some program fill in the values

coor[[i++]] = {0., 0., 0.};
coor[[i++]] = {0.1, 0.1, 0.003};


Finally, delete the remaining Null-values:

DeleteCases[coor, Null]


{{0., 0., 0.}, {0.1, 0.1, 0.003}}

This should be significantly faster

-
thank you, I don't know why I haven't thought of this option - I've already used it in other cases. however I've already implemented the Reap/Sow thing. How does it compare with your suggestion? –  Tom83B Jun 8 '14 at 11:41
Actually ConstantArray[{0.,0.,0.},len] would probably be better to prealocate –  Ajasja Jun 8 '14 at 11:57
@Tom83B Using limit = 0; Reap[While[limit < 10^5, r = RandomInteger[9]; limit += r; Sow[r]]] and comparing it with my answer I found that Reap/Sow is slightly faster. –  eldo Jun 8 '14 at 12:32
@Ajasja Or even ConstantArray[0., {len, 3}]. –  Michael E2 Jun 9 '14 at 2:08

I think using linked lists is usually the best way to proceed in cases like this.

coords = {};


Each time you generate a new point, r, add it with

coords = {coords, r};


This is very fast, but will generate a deeply nested list. When all the points have been generated, flatten and re-partition the list, which is also very fast.

coords = Partition[Flatten[coords], 3];

-