; docformat = 'rst' ; ; NAME: ; WEIGHTED_MEAN ; PURPOSE: ; Compute the arithmetic mean of an array, modulated by weights ; ;+ ; :Description: ; Compute the arithmetic mean 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 mean of VAL ; ; :Examples: ; Compute the weighted average value of the following array [1,2,3,4,5], ; using weights of [0,0,1,1,1], and compare with a simple mean:: ; IDL> val = [1,2,3,4,5] ; IDL> w = [0,0,1,1,1] ; IDL> print, weighted_mean(val,w), mean(v) ; ; :Author: ; B.Carry (IMCCE) ; ; :History: ; Change History:: ; Original Version written in 2008, B. Carry (ESO/LESIA) ; 2013-Sep : B.Carry (IMCCE) - Code cleaned ;-;- function weighted_mean, 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 return, -1 ;--II-- Singular array if nbV eq 1 then return, val ;--III-- Return the weighted mean return, total( val*weight*1., /NAN ) / total( weight*1., /NAN ) end