[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-gsl] Find variance - covariance matrix of a matrix
From: |
Francesco Abbate |
Subject: |
Re: [Help-gsl] Find variance - covariance matrix of a matrix |
Date: |
Tue, 9 Mar 2010 11:20:45 +0100 |
2010/3/9 Srimal Jayawardena <address@hidden>:
> Hi
>
> Is there a simple function/method for me to obtain the variance -
> covariance matrix of a given matrix.
>
> I'm looking for the  equivalent of 'cov' in MATLAB
Here what the Matlab documentation says:
------
C = cov(x) where x is a vector returns the variance of the vector
elements. For matrices where each row is an observation and each
column a variable, cov(x) is the covariance matrix. diag(cov(x)) is a
vector of variances for each column, and sqrt(diag(cov(x))) is a
vector of standard deviations.
------
So actually what Matlab calculates is the covariance between each of
the column vectors.
Here a simple routine that, given a matrix m, calculates the
covariance matrix by in the matrix r.
void
cov_calculate(gsl_matrix *r, gsl_matrix *m)
{
gsl_vector_view a, b;
size_t i, j;
for (i = 0; i < m->size1; i++) {
for (j = 0; j < m->size2; j++) {
double v;
a = gsl_matrix_column (m, i);
b = gsl_matrix_column (m, j);
v = gsl_stats_covariance (a.vector.data, a.vector.stride,
b.vector.data, b.vector.stride, a.vector.size);
gsl_matrix_set (r, i, j, v);
}
}
}
Note that the function gsl_stats_covariance does not works with
vectors or matrices but only with double pointer. This is why we need
to take directly the "data" field of the vector struct.
Best regards,
Francesco