Skip to content

Instantly share code, notes, and snippets.

@charlesreid1
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlesreid1/365ba77ca0bb14a62ec6 to your computer and use it in GitHub Desktop.
Save charlesreid1/365ba77ca0bb14a62ec6 to your computer and use it in GitHub Desktop.
Correlation coefficient for two T-dimensional vectors
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include <string>
using namespace std;
/// The sums() function computes several sums from vectors x and y,
/// and stores the values in a, b, c, d, and e
void sums(double* x, double* y, int T,
double* a, double* b, double* c, double* d, double* e);
int main(void) {
// FIXME
double* x = new double[T];
double* y = new double[T];
// Read data from a CSV file
// (via http://j.mp/1lu215m)
ifstream file( "data.csv" );
string line;
int line_counter = 0;
while( getline( file, line ) ) {
istringstream iss( line );
string result;
getline( iss, result, ',' );
x[line_counter] = atoi( result.c_str() );
getline( iss, result, ',' );
y[line_counter] = atoi( result.c_str() );
}
// Allocate space for sums
double a, b, c, d, e;
a = 0.0; b = 0.0; c = 0.0; d = 0.0; e = 0.0;
sums(x,y,T,&a,&b,&c,&d,&e);
// Plug the sums into the correlation coefficient formula
double r = (T*c - a*b)/sqrt((T*d - a*a)*(T*e - b*b));
delete[] x;
delete[] y;
cout << " r = " << r << "\n";
return 0;
}
void sums( double* x,
double* y,
int T,
double* a,
double* b,
double* c,
double* d,
double* e)
{
double sum_x = 0.0;
double sum_y = 0.0;
double sum_xy = 0.0;
double sum_x2 = 0.0;
double sum_y2 = 0.0;
for( unsigned long t=0; t < T; ++t ) {
sum_x += x[t];
sum_y += y[t];
sum_xy += x[t] * y[t];
sum_x2 += x[t]*x[t];
sum_y2 += y[t]*y[t];
}
*a = sum_x;
*b = sum_y;
*c = sum_xy;
*d = sum_x2;
*e = sum_y2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment