2
$\begingroup$

Suppose I have this nestlist t={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} How to calculate c=t(i)+t(i+1)

$\endgroup$
4
$\begingroup$

A pretty general way of attacking problems like this that involve filtering data is to use ListConvolve. For this specific problem:

t = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

ListConvolve[{1, 1}, t]

{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
$\endgroup$
4
$\begingroup$
t = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Most[t] + Rest[t]

   (* or *)

t[[;;-2]] + t[[2;;]]

{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}

{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}

$\endgroup$
4
$\begingroup$

It can be done very nicely by the function almost everybody forgets about.

t = Range[0, 10];
FoldPairList[{#1 + #2, #2}&, t]
{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
$\endgroup$
3
$\begingroup$
t = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

seq = Total /@ Partition[t, 2, 1]

(* {1, 3, 5, 7, 9, 11, 13, 15, 17, 19} *)

To find the general term of the sequence

c[n_] = FindSequenceFunction[seq, n]

(* -1 + 2 n *)

Verifying,

c /@ Range[Length[seq]] == seq

(* True *)

EDIT: Alternatively,

Clear[c, t]

eqns = {c[n] == t[n] + t[n + 1], t[n] == t[n - 1] + 1, t[1] == 0, t[2] == 1};

sol = RSolve[eqns, {c, t}, n][[1]]

(* {c -> Function[{n}, -1 + 2 n], t -> Function[{n}, -1 + n]} *)

Verifying the solutions,

eqns /. sol

(* {True, True, True, True} *)

c[n] /. sol

(* -1 + 2 n *)
$\endgroup$
2
$\begingroup$
MovingMap[Total, Range[0, 10], 1]

(* Out: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19} *)
$\endgroup$
2
$\begingroup$
t[[1 ;; Length@t - 1]] + t[[2 ;; Length@t]]

Or you can use Drop instead.

$\endgroup$
  • $\begingroup$ Actually what I first thought about was sum(i+j for i, j in zip(t,t[1:])) , and I wrote it in mma code. $\endgroup$ – wuyudi Dec 2 '20 at 6:15
1
$\begingroup$

This?

t = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Plus @@@ Partition[t, 2, 1]

Or

t = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
MovingMap[Total, t, 1]

{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}

$\endgroup$
  • 1
    $\begingroup$ t = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Table[t[[i]] + t[[i + 1]], {i, 1, Length@t - 1}] maybe suitable for beginner. $\endgroup$ – cvgmt Dec 2 '20 at 2:25

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