1 /*  _________________________________________________________________________
2  *
3  *  UTILIB: A utility library for developing portable C++ codes.
4  *  Copyright (c) 2008 Sandia Corporation.
5  *  This software is distributed under the BSD License.
6  *  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
7  *  the U.S. Government retains certain rights in this software.
8  *  For more information, see the README file in the top UTILIB directory.
9  *  _________________________________________________________________________
10  */
11 
12 /* cov.c
13  *
14  * Routine to compute the covariance of a matrix
15  */
16 
17 int covariance(double **X, int m, int n, double **COV);
18 
covariance(double ** X,int m,int n,double ** COV)19 int covariance(double **X, int m, int n, double **COV)
20 {
21 int i,j,k,l;
22 double *temp_vec;
23 
24 temp_vec = COV[0];
25 
26 /* Compute the Means */
27 for (i=0; i<n; i++) {
28   temp_vec[i] = 0.0;
29   for (j=0; j<m; j++)
30     temp_vec[i] += X[j][i];
31   temp_vec[i] /= ((double) m);
32   }
33 
34 /* Subtract out the means */
35 for (i=0; i<n; i++)
36   for (j=0; j<m; j++)
37     X[j][i] -= temp_vec[i];
38 
39 /* Compute E[(X1 - mu1)*(X2 - mu2)]  */
40 for (k=0; k<n; k++)
41   for (l=0; l<=k; l++) {
42     COV[k][l] = 0.0;
43     for (j=0; j<m; j++)
44       COV[k][l] += X[j][k]*X[j][l];
45     COV[k][l] /= ((double) (m-1));
46     COV[l][k] = COV[k][l];
47   }
48 
49 return 0;
50 }
51