Re: fast way of appending x zeros to a list?
- To: mathgroup at smc.vnet.net
- Subject: [mg79145] Re: fast way of appending x zeros to a list?
- From: David Bailey <dave at Remove_Thisdbailey.co.uk>
- Date: Thu, 19 Jul 2007 03:41:23 -0400 (EDT)
- 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.
>
> At the moment I use: Do[PrependTo[data,0],{K}] where the K depends on
> certain factors.
>
> 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.
>
>
Hello,
PadLeft can indeed be used to prepend K zeros to a list:
s={a,b,c};
K=5;
PadLeft[s,K+Length[s]]
You are right - appending and pre-pending to lists is not recommended
for speed, but with Mathematica you always have to ask yourself whether
speed matters in your particular application. For example:
K=1000;
Do[PrependTo[s, 0], {K}] // Timing
Takes all of 0.02 seconds on my machine!
David Bailey
http://www.dbaileyconsultancy.co.uk