Covariance and correlation

Covariance and correlation

The Fortran Standard library stdlib provides several procedures to compute covariances and Pearson correlations of the elements of an array along a dimension.

This guide shows examples to compute covariances and Pearson correlations from an array. All the functions described in this tutorial can be accessed via the stdlib_stats module.

Covariance

The Fortran Standard library stdlib provides the function cov for computing the covariance of the elements of an array along a dimension:

cov.f90
program cov
  use stdlib_stats, only: cov
  implicit none
  real :: y(1:2, 1:3) = reshape([1., 2., 3., 4., 5., 6.], [2, 3])

  print*, cov(y, 1)
  print*, cov(y, 2)
end program cov

Note

The default scaling of the covariance is n-1. However, it can be scaled with n by setting the optional argument corrected to .false..

Pearson correlation

The Fortran Standard library stdlib provides the function corr for computing the Pearson correlation of the elements of an array along a dimension:

corr.f90
program corr
  use stdlib_stats, only: corr
  implicit none
  real :: y(1:2, 1:3) = reshape([1., 2., 3., 4., 5., 6.], [2, 3])

  print*, corr(y, 1)
  print*, corr(y, 2)
end program corr

Note

Like other procedures in the stdlib_stats module, the functions for computing covariances and correlations of array elements support an optional mask to ignore some elements of the array.