1
$\begingroup$

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}...}
$\endgroup$
2
  • 2
    $\begingroup$ Developer`PartitionMap[Mean, y, 3] $\endgroup$
    – Kuba
    Commented Nov 20, 2015 at 13:55
  • $\begingroup$ closely related 28240, even more general: 4061 $\endgroup$
    – Kuba
    Commented Nov 20, 2015 at 14:02

3 Answers 3

2
$\begingroup$

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] )

$\endgroup$
3
$\begingroup$
y = {{a}, {b}, {c}, {d}, {e}, {f}, {g}, {h}}     
MovingAverage[y, 3][[;; ;; 3]]
$\endgroup$
1
$\begingroup$
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

$\endgroup$
2
  • $\begingroup$ You've put wrong output :) $\endgroup$
    – Kuba
    Commented Nov 20, 2015 at 14:07
  • $\begingroup$ Indeed, hard to see :) $\endgroup$
    – eldo
    Commented Nov 20, 2015 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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