Re: Operating on every k-th element of list?
- To: mathgroup at smc.vnet.net
- Subject: [mg37089] Re: Operating on every k-th element of list?
- From: "Allan Hayes" <hay at haystack.demon.co.uk>
- Date: Wed, 9 Oct 2002 05:25:38 -0400 (EDT)
- References: <anufl8$ap2$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
lst= Range[14] {1,2,3,4,5,6,7,8,9,10,11,12,13,14} A list of positions in lst ( for your purpose Range[1, Length[lst], 3] will do) ps= {3,5,10}; The following applies h to each ps element in lst and adds the result to the following element (lst[[ps+1]]=h/@lst[[ps]]+lst[[ps+1]];lst) {1,2,3,4+h[3],5,6+h[5],7,8,9,10,11+h[10],12,13,14} -- Allan --------------------- Allan Hayes Mathematica Training and Consulting Leicester UK www.haystack.demon.co.uk hay at haystack.demon.co.uk Voice: +44 (0)116 271 4198 Fax: +44 (0)870 164 0565 "AES" <siegman at stanford.edu> wrote in message news:anufl8$ap2$1 at smc.vnet.net... > I want to apply a function to every k-th element of a long list and > add the result to the k+1 element. > > [Actually k = 3 and I just want to multiply myList[[k]] by a > constant (independent of k) and add the result to myList[[k+1]] for > every value of k that's divisible by 3.] > > Is there a way to do this -- or in general to get at every k-th > element of a list -- that's faster and more elegant than writing a brute > force Do[] loop or using Mod[] operators, and that will take > advantage of native List operators, but still not be too recondite? > > I've been thinking about multiplying a copy of myList by a "mask list" > {0,0,1,0,0,1,..} to generate a "masked copy" and approaches like that. > Better ways??? >