1

I have a list f,

y={{a},{b},{c},{d},{e},{f},{g},{h}...}

I want to sum the first 3 in this list and divide that value by 3 and append to a new list. Then repeat for the next three values. Then repeat...

So my final list will be,

y2={{(a+b+c)/3},{(d+e+f)/3},{(g+h+i)/3}...}
Scott R
  • 121
  • 4

3 Answers3

3
y = {{a}, {b}, {c}, {d}, {e}, {f}, {g}, {h}}     
MovingAverage[y, 3][[;; ;; 3]]
yarchik
  • 18,202
  • 2
  • 28
  • 66
2

Mathematica tends to involve modifying the whole list until you get the thing you want rather than looping and contracting new lists.

This is how I would think about it:

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

Get rid of the inside lists

Flatten[y]

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

Divide lists up uses Partition

Partition[Flatten[y],3]

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

I'm assuming you're adding 3 elements and diving by three to get a mean? I'll use Mean.

Mean/@Partition[Flatten[y],3]

{1/3 (a + b + c), 1/3 (d + e + f), 1/3 (g + h + i), 1/3 (j + k + l)}

( This is short for Map[Mean, Partition[Flatten[y],3]] )

Then to get each element wrapped in a list as in your answer:

Transpose[{Mean/@Partition[Flatten[y],3]}]

{{1/3 (a + b + c)}, {1/3 (d + e + f)}, {1/3 (g + h + i)}, {1/ 3 (j + k + l)}}

( Alternatively List/@Mean/@Partition[Flatten[y],3] )

1
Clear[a, b, c, d, e, f, g, h]

y = {{a}, {b}, {c}, {d}, {e}, {f}, {g}, {h}, {i}};

Mean /@ Partition[Flatten @ y, 3]

enter image description here

eldo
  • 67,911
  • 5
  • 60
  • 168