Re: Operating on every k-th element of list?
- To: mathgroup at smc.vnet.net
- Subject: [mg37096] Re: [mg37080] Operating on every k-th element of list?
- From: Omega Consulting <omega_consulting at yahoo.com>
- Date: Wed, 9 Oct 2002 05:25:50 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
At 06:17 AM 10/8/2002, 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.] lst = Table[Random[], {20}] fact = 2 Here's a matrix method. f represents an indexed element of a matrix. f[x_,x_] := If[Mod[x,3]==0, fact, 1] f[x_, y_] := If[Mod[x,3]==0&&y\[Equal]x+1, 2, 0] Create a matrix from the elements. arr = Array[f,{Length[lst], Length[lst]}]; Then matrix multiply. newlst1 = lst.arr Here's another way with the highly underrated MapIndexed. Create pairs of the nth and n-1th values. pairs = Transpose[{lst, Prepend[Drop[lst,-1],0]}] Create a function that takes the nth value (val), the n-1th value (prevval), and the index (num). multlst[{val_, prevval_}, {num_}] := Switch[Mod[num, 3], 0, fact*val, 1,val+ fact*prevval, 2, val ] Then, MapIndexed across the pairs. newlst2=MapIndexed[multlst, pairs] -------------------------------------------------------------- Omega Consulting "The final answer to your Mathematica needs" Spend less time searching and more time finding. http://www.wz.com/internet/Mathematica.html