// Linear Regression Example for Arduino
void setup() {
Serial.begin(9600);
// Sample data
float x[] = {118,1524,2688,3800,4970,6317,7423,9240,10875,12045,13216,14504,16315,17656,19474};
float y[] = {2,26,46,65,85,108,127,158,186,206,226,248,279,302,333};
// Number of data points
int n = sizeof(x) / sizeof(x[0]);
// Calculate the slope and y-intercept
float slope, intercept;
linearRegression(x, y, n, slope, intercept);
// Display the results
Serial.print("Slope: ");
Serial.println(slope, 4);
Serial.print("Intercept: ");
Serial.println(intercept, 4);
}
void loop() {
// Nothing to do in the loop for this example
}
// Function to calculate linear regression using the least squares method
void linearRegression(float x[], float y[], int n, float &slope, float &intercept) {
float sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
for (int i = 0; i < n; i++) {
sumX += x[i];
sumY += y[i];
sumXY += x[i] * y[i];
sumX2 += x[i] * x[i];
}
slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
intercept = (sumY - slope * sumX) / n;
}