Skip to content

Instantly share code, notes, and snippets.

@dmgerman
Last active September 22, 2015 01:47
Show Gist options
  • Save dmgerman/ce1a06bd2641983fc000 to your computer and use it in GitHub Desktop.
Save dmgerman/ce1a06bd2641983fc000 to your computer and use it in GitHub Desktop.
drop function if exists _final_mdnif(int[]) cascade;
CREATE OR REPLACE FUNCTION _final_mdnif(int[])
RETURNS numeric AS
$$
DECLARE
sum numeric;
i int;
j int;
N int;
K int;
BEGIN
sum := 0;
K = array_length($1,1);
-- undefined for zero arrays
IF K = 0 OR K IS NULL THEN
RETURN NULL;
END IF;
-- equal to 0 if one only
IF K = 1 THEN
RETURN 0;
END IF;
-- compute N
N = 0;
FOR i IN 1..K LOOP
N := N + $1[i];
END LOOP;
-- otherwise compute according to Wilcox paper
FOR i IN 1..K-1 LOOP
FOR j IN i+1..K LOOP
sum := sum + @($1[i] - $1[j]);
END LOOP;
END LOOP;
RETURN 1.0 - (1.0/(N * (K-1))) * sum;
END
$$
LANGUAGE 'plpgsql' IMMUTABLE;
CREATE AGGREGATE mdnif(int) (
SFUNC=array_append,
STYPE=int[],
FINALFUNC=_final_mdnif,
INITCOND='{}'
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment