0
$\begingroup$

If I have a list {3,19.5,85,45/2,5.6}, how can I select the median of the list without using the built-in Median command?

First I sorted the list

Sort[{3,19.5,85,45/2,5.6}]
{3, 5.6, 19.5, 45/2, 85}

I can't figure out which command to use to select the median without directly using Median command.

$\endgroup$
4
  • 2
    $\begingroup$ Use Part (shortcut [[ ]]) to take the term that is at the position (Length[list]+1)/2 $\endgroup$ – bill s Nov 14 '20 at 14:01
  • 1
    $\begingroup$ Quantile[{1, 2, 3, 4, 5, 6, 7}, 1/2] $\endgroup$ – wuyudi Nov 14 '20 at 14:03
  • 1
    $\begingroup$ Duplicate. See this question. $\endgroup$ – Alan Nov 14 '20 at 15:18
  • 1
    $\begingroup$ Ummm... just wondering: why not use Median? $\endgroup$ – David G. Stork Nov 14 '20 at 19:51
0
$\begingroup$

If the length of the list is odd, then the median is the middle element of the sorted list. If the length of the list is even, the median is the average of the two "central" values:

myMedian[x_List] := (z = Sort[x];
  len = Length[z];
  If[OddQ[len], z[[(len + 1)/2]], (z[[len/2]] + z[[len/2 + 1]])/2])
$\endgroup$
0
$\begingroup$

Just for fun, here's a rendering into Mathematica of a very old idiom from the APL programming language (see https://aplwiki.com/wiki/FinnAPL_idiom_library#cite_note-1) that requires no explicit splitting into odd/even cases:

    myMedian[lis_] := (1/2) Total[Sort[lis][[Abs@Ceiling[{-1/2, 1/2} (1 + Length@lis)]]]]

Tests:

    x = RandomInteger[{2, 50}, RandomInteger[{4, 8}]];
    Sort[x]
    {myMedian[x], Median[x]}
(* {4, 9, 31, 34, 39, 40, 40, 44} *)
(* 73/2, 73/2 *)

    x = RandomInteger[{2, 50}, RandomInteger[{4, 8}]];
    Sort[x]
    {myMedian[x], Median[x]}
(* {2, 16, 16, 18, 24, 26, 42} *)
(* 18, 18 *)
$\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.