Created
April 2, 2015 13:41
-
-
Save j-faria/35fe65b18a661b9e19ea to your computer and use it in GitHub Desktop.
Calculate the Pearson correlation coefficient of two arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
real(kind=8) function pearsonr(x, y) result(r) | |
! given two arrays x and y, this function computes their Pearson correlation coefficient r | |
implicit none | |
real(kind=8), dimension(:) :: x, y | |
real(kind=8), dimension(size(x)) :: xt, yt | |
real(kind=8) :: ax, ay, df, sxx, sxy, syy | |
integer :: n | |
if (size(x) /= size(y)) STOP 'Dimension mismatch in pearsonr' | |
n = size(x) | |
! find the means and subtract them | |
ax = sum(x)/n | |
ay = sum(y)/n | |
xt = x - ax | |
yt = y - ay | |
sxx = dot_product(xt,xt) | |
syy = dot_product(yt,yt) | |
sxy = dot_product(xt,yt) | |
r = sxy / sqrt(sxx*syy) | |
! abs(r) cannot be > 1, except for artifacts of floating point arithmetic | |
r = max(min(r, 1.d0), -1.d0) | |
end function pearsonr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment