3
$\begingroup$

Suppose that I have three lists:

list1 = {{0, 1}, {0.1, 10}, {0.2, 100}};
list2 = {{0, 1}, {0.1, 10}, {0.2, 100}};
list3 = {{0, 2}, {0.1, 20}, {0.2, 200}};

In each list, the abscissas represent time (my system was measured at the times 0, 0.1, and 0.2 seconds, for example), whereas the ordinates are the measured values.

I would like to create a function f that finds the average (i.e., the mean) of the ordinates. So:

f[list1, list2, list3]

should give the output:

{{0, 4/3}, {0.1, 40/3}, {0.2, 400/3}}

I would like f to be able to take two or more lists as input. All lists are given to have the same number of points.

I think that one way to write f is:

f[lists__] := Transpose[{First[{lists}][[All, 1]], 
  Map[Mean, Transpose[Map[#[[All, 2]] &, {lists}]]]}]

Can you please help me think of a cleaner, more succinct, and possibly faster way to do this?

$\endgroup$
  • $\begingroup$ f[a_, b_, c_] := Mean[{a, b, c}]. So f[list1, list2, list3] returns {{0, 4/3}, {0.1, 40/3}, {0.2, 400/3}}. Is this what you wanted ? $\endgroup$ – Artes Sep 18 '12 at 20:24
  • $\begingroup$ @Artes Yes, except that I would like f to take an arbitrary number of lists. $\endgroup$ – Andrew Sep 18 '12 at 20:27
10
$\begingroup$

You could just do:

f[list__] := Plus[list]/Length@{list}

or simpler, using the built-in Mean:

f[list__] := Mean[{list}]

Using this with your example:

f[list1, list2, list3]
(* {{0, 4/3}, {0.1, 40/3}, {0.2, 400/3}} *)
$\endgroup$
  • 1
    $\begingroup$ (+1) ... or f=Mean[{##}]&. $\endgroup$ – kglr Sep 18 '12 at 21:53
  • 1
    $\begingroup$ ...or Composition[Mean, List][list1, list2, list3]. $\endgroup$ – J. M. is in limbo Sep 19 '12 at 7:45

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.