// The Wikipedia example
// http://en.wikipedia.org/wiki/Simple_linear_regression
//
float x[] = {33, 83, 130.33, 181, 231.33, 278.33};
float y[] = {50, 100, 150, 200, 250, 300};
int xNum = sizeof(x) / sizeof(float);
int yNum = sizeof(y) / sizeof(float);
float lrCoef[2] = {0, 0};
// initialize variables
float sum_x = 0;
float sum_y = 0;
float sum_xy = 0;
float sum_xx = 0;
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(3, INPUT);
delay(200);
// call simple linear regression algorithm
simpLinReg(x, y, lrCoef, xNum);
Serial.println("Wikipedia example should give: beta= 61.272, alpha= -39.062");
Serial.println();
Serial.println("Calculated coefficients:");
Serial.println(" BETA ALPHA");
Serial.print("f(x)= ");
//Serial.print("BETA: ");
Serial.print(lrCoef[0], 4);
//Serial.print(", ALPHA");
if (lrCoef[1] > 0) {
Serial.print("*x + ");
}
else {
Serial.print("*x ");
}
Serial.println(lrCoef[1], 4);
}
int alr = 0;
int lsAlr = 0;
int step = 0;
bool readComplete = false;
// void loop() {
// // if(!digitalRead(2)){
// // readComplete = false
// // step ++;
// // }
// if (step == 0 && !readComplete) {
// alr = analogRead(A0);
// if (abs(alr - lsAlr) / alr < 0.02) {
// x[]
// step ++;
// }
// }
// // Serial.println("2");
// if (!digitalRead(3))Serial.println("3");
// }
void simpLinReg(float* x, float* y, float* lrCoef, int n) {
// pass x and y arrays (pointers), lrCoef pointer, and n. The lrCoef array is comprised of the slope=lrCoef[0] and intercept=lrCoef[1]. n is length of the x and y arrays.
// http://en.wikipedia.org/wiki/Simple_linear_regression
// calculations required for linear regression
for (int i = 0; i < n; i++) {
sum_x = sum_x + x[i];
sum_y = sum_y + y[i];
sum_xy = sum_xy + x[i] * y[i];
sum_xx = sum_xx + x[i] * x[i];
}
// simple linear regression algorithm
lrCoef[0] = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);
lrCoef[1] = (sum_y / n) - ((lrCoef[0] * sum_x) / n);
}