Re: fast way of appending x zeros to a list?
- To: mathgroup at smc.vnet.net
- Subject: [mg79108] Re: fast way of appending x zeros to a list?
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Thu, 19 Jul 2007 03:22:12 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <f7ke8n$508$1@smc.vnet.net>
kristoph wrote: > Dear all, > > I'm looking for a fast way to append 0's to a list. Unfortunately, I > append a variable number of 0's to a list which is generated by a > For[...]-loop. Therefore, PadLeft[...] is not variable enough to > append exactly x zeros to the list. Are you sure you are not fooling yourself? (I would like to see your code with PadLeft...) > At the moment I use: Do[PrependTo[data,0],{K}] where the K depends on > certain factors. See below for an example with PadLeft that do the same think that the above code but at the speed of light :-) > In case you have an idea to append exactly x zeros to the left quickly > I would be more that happy since I heard that the PrependTo[...] and > AppendTo[...] functions are very slow. > > Thanks a lot. First, we check that both approaches gives the same final list. In[1]:= data = RandomChoice[{a, b, c}, {10}] With[{K = 3}, Do[PrependTo[data, 0], {K}]] data Out[1]= {c, b, c, b, a, c, c, c, a, c} Out[3]= {0, 0, 0, c, b, c, b, a, c, c, c, a, c} In[4]:= data = RandomChoice[{a, b, c}, {10}] With[{K = 3}, data = PadLeft[data, Length[data] + K]] Out[4]= {b, a, b, c, a, b, c, a, b, a} Out[5]= {0, 0, 0, b, a, b, c, a, b, c, a, b, a} Now we compare the respective speeds. Inserting 30000 zeros takes over 20 seconds for the do loop thing, while PadLeft is still so fast that the timing returns 0 second. In[6]:= data = RandomChoice[{a, b, c}, {10000}]; Timing[With[{K = 30000}, Do[PrependTo[data, 0], {K}]]][[1]] Out[7]= 22.109 In[8]:= data = RandomChoice[{a, b, c}, {10000}]; Timing[With[{K = 30000}, data = PadLeft[data, Length[data] + K]]][[1]] Out[9]= 1.38778*10^-17 Regards, Jean-Marc