Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2002
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

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: [mg37092] RE: [mg37080] Operating on every k-th element of list?
  • From: "DrBob" <drbob at bigfoot.com>
  • Date: Wed, 9 Oct 2002 05:25:42 -0400 (EDT)
  • Reply-to: <drbob at bigfoot.com>
  • Sender: owner-wri-mathgroup at wolfram.com

Here's a start, with a more complicated function:

lst = Range[50]; 
f = #1^2 & ; 
k = 7; 
r = Range[k + 1, Length[lst], k]; 
lst[[r]] = lst[[r]] + f /@ lst[[r - 1]]; 
lst

{1, 2, 3, 4, 5, 6, 7, 57, 9, 10, 11, 12, 13, 14, 211, 16, 17, 18, 19,
20, 21, 463, 23, 24, 25, 26, 27, 28, 813, 30, 31, 32, 33, 34, 35, 1261,
37, 38, 39, 40, 41, 42, 1807, 44, 45, 46, 47, 48, 49, 2451}

or:

g[lst_List, k_Integer?Positive, f_Function] := Module[
    {result = lst, r = Range[k + 1, Length[lst], k]},
    result[[r]] = result[[r]] + f /@ lst[[r - 1]]; 
    result
    ]
lst = Range[50]; 
lst = g[lst, 7, #1^2 & ]

or:

lst = Range[50]; 
lst + Drop[Prepend[MapIndexed[If[Mod[First@#2, k] == 0, f@#1, 0] &,
lst], 0], -1]

DrBob

-----Original Message-----
From: AES [mailto:siegman at stanford.edu] 
To: mathgroup at smc.vnet.net
Subject: [mg37092] [mg37080] Operating on every k-th element of list?


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





  • Prev by Date: Successive Approximation
  • 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?