G
Gary Wessle
Hi
I wrote a code to calculate the correlation between 2 sequence of
double numbers presented as vectors.
did I go about this the right way?
thanks
#include <vector>
using std::vector;
#include <valarray>
using std::valarray;
cor::cor(vector<double>& x, vector<double>& y)
{
int c = x.size();
int d = y.size();
if(c != d)
cout << "to calculate correlation, variables"
" must be of the same number of elements" << endl;
// converts the input to valarray for spead and ellegance.
valarray<double> a(c);
valarray<double> b(d);
copy(x.begin(), x.end(), &a[0]);
copy(y.begin(), y.end(), &b[0]);
// expected values "mean"
double Ea = a.sum() / static_cast<double> (a.size());
double Eb = b.sum() / static_cast<double> (b.size());
// standard diviation
double Sa = sqrt( pow((a-Ea),2).sum()/c );
double Sb = sqrt( pow((b-Eb),2).sum()/d );
// double Sb = sqrt( ((a*a).sum()/c)- pow(Ea, 2) ); // faster
// but more round-offs
// correlation
cof = ( ((a-Ea)/Sa)*((b-Eb)/Sb) ).sum()/(c-1);
}
I wrote a code to calculate the correlation between 2 sequence of
double numbers presented as vectors.
did I go about this the right way?
thanks
#include <vector>
using std::vector;
#include <valarray>
using std::valarray;
cor::cor(vector<double>& x, vector<double>& y)
{
int c = x.size();
int d = y.size();
if(c != d)
cout << "to calculate correlation, variables"
" must be of the same number of elements" << endl;
// converts the input to valarray for spead and ellegance.
valarray<double> a(c);
valarray<double> b(d);
copy(x.begin(), x.end(), &a[0]);
copy(y.begin(), y.end(), &b[0]);
// expected values "mean"
double Ea = a.sum() / static_cast<double> (a.size());
double Eb = b.sum() / static_cast<double> (b.size());
// standard diviation
double Sa = sqrt( pow((a-Ea),2).sum()/c );
double Sb = sqrt( pow((b-Eb),2).sum()/d );
// double Sb = sqrt( ((a*a).sum()/c)- pow(Ea, 2) ); // faster
// but more round-offs
// correlation
cof = ( ((a-Ea)/Sa)*((b-Eb)/Sb) ).sum()/(c-1);
}