; docformat = 'rst' ; ; NAME: ; weighted_median ; PURPOSE: ; Compute the arithmetic median of an array, modulated by weights ; ;+ ; :Description: ; Compute the arithmetic median of an array, modulated by weights ; ; :Categories: ; Maths, Moment ; ; :Params: ; VAL: in, required, type=float ; An array of values for which the average is sought ; WEIGHT: in, required, type=float ; An array of the weight for each element in VAL ; ; :Returns: The weighted arithmetic median of VAL ; ; :Examples: ; Compute the weighted median value of the following array [1,2,3,4,5], ; using weights of [0,0,1,1,1], and compare with a simple median:: ; IDL> val = [1,2,3,4,5] ; IDL> w = [0,0,1,1,1] ; IDL> print, weighted_median(val,w), median(v) ; ; :Author: ; B.Carry (IMCCE) ; ; :History: ; Change History:: ; Original Version written in September 2014, B. Carry (IMCCE) ;-;- function weighted_median, val, weight ;--I-- Bullet-proof checks if n_params() lt 2 then begin message,/ioerror, 'Syntax: result = weighted_median(val, weight)' return, -1 endif nbV = n_elements( val ) nbW = n_elements( weight ) if nbV ne nbW then begin message,/ioerror, 'Input vector have incompatible lengths' return, -1 endif ;--II-- Singular array if nbV eq 1 then return, val ;--III-- Return the weighted mean ;--III.1-- Order Inputs ord = sort(val) oV = val(ord) oW = weight(ord) ;--III.2-- Sum of Weights S = total(oW) ;--III.3-- Find Median Index k=0L sum = S-oW(0) while sum ge S/2. do begin k++ sum -= oW(k) endwhile return, oV(k) end