2
$\begingroup$

I have a list of the type list={1,2...,n,n+1,...,2n,2n+1,...,3n,..} and I want to create a new list with the sum of certain elements of the list, in the way newlist = {1+(n+1)+(2n+1)...,2+(2n+1)+(3n+1)...}, for example:

list = {1,2,3,4,5,1,2,3,4,5,1,2,3,4,5}, newlist={1+1+1,2+2+2,3+3+3,4+4+4,5+5+5},

I tried using listnew1=Table[Take[list[[i,1]],{i,1,n}], listnew2=Table[Take[list[[i,1]],{i,n+1,2n}] and so on, and then

total=listnew1+listnew2 +...

the problem comes for a several listnew (in my case around 1000)

is there a way to this in mathematica automatically? Thanks for the help,

$\endgroup$
  • $\begingroup$ So you have a list of length $k\cdot n$ and want to sum every $n$th element to produce a list of $k$ such sums? $\endgroup$ – corey979 Sep 8 '16 at 17:09
  • 1
    $\begingroup$ If it's every fifth element, then Total@Partition[list, 5]. If it's every nth element, then Total@Partition[list, n]. $\endgroup$ – march Sep 8 '16 at 17:13
4
$\begingroup$

If it's every nth element, then

Total@Partition[list, n]

works. For example:

lst = Array[a, 12]
Total@Partition[lst, 4]
(* {a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12]}
(* {a[1] + a[5] + a[9], a[2] + a[6] + a[10], a[3] + a[7] + a[11], a[4] + a[8] + a[12]} *)

Less elegantly, using Table and Sum:

With[{n = 4},
  Table[Sum[lst[[jj + kk]], {kk, 1, Length@lst, n}], {jj, 0, n - 1}]
 ]
$\endgroup$
1
$\begingroup$

A different approach might be

n = 3;
Total /@ Table[list[[i ;; -1 ;; n]], {i, 1, n}]
$\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.