3
$\begingroup$

I have a list of elements

list = {a, b, c, d, e, f, g, h, i, j, k, l, ...} 

I am trying to get successive differences with step s apart. For example, for $s=3$, I am trying to get {-a + d, -d + g, -g + j, ...}.

I started with diff = Differences[list, 1, 3] which gives {-a + d, -b + e, -c + f, -d + g, -e + h, -f + i, -g + j, -h + k, -i + l}. Then I apply Take[diff, {1, -1, 3}] which gives me my desired values.

Is there any way to optimise this code for larger lists?

Thanks

$\endgroup$
4
  • 1
    $\begingroup$ I think Differences@list[[;; ;; 3]] is what you want. $\endgroup$ Commented Jun 11, 2016 at 5:48
  • $\begingroup$ @yode Thank you $\endgroup$ Commented Jun 11, 2016 at 5:51
  • 1
    $\begingroup$ @yode, that's going to be hard to outdo, so I think you can post that as an answer. :) $\endgroup$ Commented Jun 11, 2016 at 6:00
  • $\begingroup$ @J.M. Done.. :) $\endgroup$ Commented Jun 11, 2016 at 6:05

3 Answers 3

9
$\begingroup$

I don't sure the OP appreciate this result.So I make it as a comment.Since the OP content with it,so I post it as a answer for reader.

list = CharacterRange["a", "z"] 

{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}

Differences@list[[;; ;; 3]] 

{-a+d,-d+g,-g+j,-j+m,-m+p,-p+s,-s+v,-v+y}

$\endgroup$
3
$\begingroup$

Using Downsample:

list = CharacterRange["a", "z"]; Differences@Downsample[list, 3] 

Other variants:

hx = (First@# - Last@#) &; hx /@ Partition[list, 4, 3] BlockMap[hx, list, 4, 3] 

{-"a" + "d", -"d" + "g", -"g" + "j", -"j" + "m", -"m" + "p", -"p" + "s", -"s" + "v", -"v" + "y"}

$\endgroup$
1
$\begingroup$

Using Extract:

Differences@Extract[list, {;; ;; 3}] 

{-"a" + "d", -"d" + "g", -"g" + "j", -"j" + "m", -"m" + "p", -"p" + "s", -"s" + "v", -"v" + "y"}

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.