MathGroup Archive 2002

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Operating on every k-th element of list?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg37085] Re: [mg37080] Operating on every k-th element of list?
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Wed, 9 Oct 2002 05:25:32 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

On Tuesday, October 8, 2002, at 07:17 AM, AES wrote:

> 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???
>
>

Here is a generalization of what you've asked:

f[l_List,c_,k_Integer,p_Integer]:=Flatten[Block[{r=#[[k]] 
c},Join[Take[#,k-1],{r,#[[k+1]]+ 
r},Drop[#,k+1]]]&/@Partition[l,p]]/;(Mod[Length[l],p]==0&&k<p)

I took the liberty of allowing you to partition the list into sublists 
of length p independent of k, for your case simply set k = 3 and p = 4. 
  c is the constant you wish to use.

Regards,

Sseziwa



  • Prev by Date: Re: Operating on every k-th element of list?
  • Next by Date: Re: Operating on every k-th element of list?
  • Previous by thread: Re: Operating on every k-th element of list?
  • Next by thread: Re: Operating on every k-th element of list?