I got the follwing code which should add a '1' 100 times to an empty list.
plotVals = {}
Do[Append[plotVals, 1], {l, 1, Nmax}];
The output is again an empty list, why is this the case?
I got the follwing code which should add a '1' 100 times to an empty list.
plotVals = {}
Do[Append[plotVals, 1], {l, 1, Nmax}];
The output is again an empty list, why is this the case?
Block[{plotVals = {}},
Do[{plotVals = Append[plotVals, 1], Print[plotVals]}, {l, 1, 5}]]
You will lose information if you simply use Append, so you need to store it.
{1} {1,1} {1,1,1}....
Also, Append/AppendTo is suicidal for speed, so rather use dynamically created list as,
Block[{plotVals = {}}, {Do[{plotVals = {plotVals, 1}}, {l, 1,
5}]}; plotVals]
{{{{{{}, 1}, 1}, 1}, 1}, 1}
Which you can flatten. It will give a much better performance than Append/AppendTo
Append is one of those for which it is somewhat non-obvious before you get used to it. Once you do grok the mostly-functional paradigm of Mathematica and tools it provides for it, you probably want to stay away from imperative constructs most of the time.
– kirma
Oct 06 '13 at 17:46
AppendTo.Appenddoesn't modify the value ofplotVals. Also take a look atConstantArray. – C. E. Oct 06 '13 at 17:20