1
$\begingroup$

Having a list as follow:

l = {x1, x2, x3, x4, x5};

I want to add each element with the element before, so I did:

Delete[Table[l[[i]] + l[[i - 1]], {i, Length[l]}], 1]

which gives:

{x1 + x2, x2 + x3, x3 + x4, x4 + x5}

I wonder if there is a better way of doing this? or is there any built-in function to do such operation?

$\endgroup$
2
$\begingroup$

So using the comments I get:

MovingMap[Total, l, 1]

that gives:

{x1 + x2, x2 + x3, x3 + x4, x4 + x5}
$\endgroup$
  • 5
    $\begingroup$ ListCorrelate[]/ListConvolve[] ought to be faster than this one. $\endgroup$ – J. M. is away Oct 16 '18 at 10:39
1
$\begingroup$

Let me make a collection of methods suggested so far, other than MovingMap (thx to @J.M.iscomputer-less for the last two):

2 MovingAverage[l, 2]
BlockMap[Total, l, 2, 1]
Total /@ Partition[l, 2, 1]
ListCorrelate[{1, 1}, l]
ListConvolve[{1, 1}, l]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.