Computes median using s_utl_rank for tie-aware ranking
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
real(kind=wp), | intent(in) | :: | x(:) |
x vector (assumed size array) |
median
pure function f_sts_median_core(x) result(median) ! ==== Description !! Computes median using s_utl_rank for tie-aware ranking ! ==== Declarations real(wp), intent(in) :: x(:) !! x vector (assumed size array) real(wp) :: median !! median real(wp), allocatable :: rx(:) !! ranks of x integer(i4) :: n !! dimension of x integer(i4) :: i1, i2 ! ==== Instructions ! get array dimension n = size(x) ! get ranks for x; rank arrays allocated in ranking call s_utl_rank(x, rx) if (mod(n, 2) .eq. 1) then ! If n is odd, the middle rank is (n+1)/2 i1 = maxloc(rx, mask = (rx .eq. real((n+1)/2, wp)), dim=1) median = x(i1) else ! If n is even, average elements with ranks n/2 and n/2+1 i1 = maxloc(rx, mask = (rx .eq. real(n, wp)/2.0_wp) , dim=1) i2 = maxloc(rx, mask = (rx .eq. 1.0_wp + real(n, wp)/2.0_wp), dim=1) median = 0.5_wp * (x(i1) + x(i2)) endif deallocate(rx) end function f_sts_median_core