• A Object to Calibrate and Scale Analog Inputs to Engineering Units( In three installments)
    Part 2 Linear Regression

    Now to add a method to perform a calibration.
    This is done by collecting data and performing a linear regression.
    Look at the numerical example in the following link:
    https://en.wikipedia.org/wiki/Simple_lin­ear_regression
    The X values are the raw analog readings and the Y values are the values from the calibration device. We need five sums:
    Sx=Sum of Xi values,
    Sy= Sum of Yi values,
    Sxx= Sum of the product Xi*Xi,
    Sxy= Sum of the product Xi*Yi, and the
    Syy =Sum of the product Yi*Yi.

    The slope is given by:
    Slope = (N*Sxy - Sx*Sy)/( NSxx - Sx Sx),
    And the Intercept is given by:
    Intercept = Sy/N - (Slope * Sx) / N, where
    N = the number of samples.

    A linear regression object is defined as follows:

    //The constructor for LinRegObj
    function LinRegObj(a,nn){
      this.Sx=0;
      this.Sy=0;
      this.Sxy=0;
      this.Sxx=0;
      this.Syy=0;
      this.N=0;
      this.A=a;
      this.NN=nn;
      this.slope=0;
      this.intercept=0;
    }//end LinRegObj
    //Methods for LinRegObj
    //LinRegObj.prototype.TakeData=function(­y){
    LinRegObj.prototype.TakeData=function(x,­y){  for(i=0;i<this.NN;i++){
    //    var x=analogRead(this.A.pin);
        this.Sx+=x;
        this.Sy+=y;
        this.Sxy+=(x*y);
        this.Sxx+=(x*x);
        this.Syy+=(y*y);
        this.N++;
      }//next i
    };//endTakeData
    
    LinRegObj.prototype.Calculate=function()­{
     this.slope=(this.N*this.Sxy-this.Sx*this­.Sy)/
       (this.N*this.Sxx - this.Sx*this.Sx);
     this.intercept=this.Sy/this.N-(this.slop­e*this.Sx)/this.N;
    //this.A.slope=this.slope;
    //this.A.Intercept=this.intercept;
    };//end Calculate
    //end LinRegObj methods
    
    //test example calculation
    var Q=new LinRegObj(1,5);
    Q.TakeData(0,0);
    Q.TakeData(1,80);
    Q.Calculate();
    console.log("Slope= ",Q.slope);
    console.log("Intercept= ",Q.intercept);
    
    

    The object is commented to omit actual analogRead() and the X values are simulated to test the math.
    The left WebIDE screen displays the following correct answer:

    >echo(0);
    Slope=  80
    Intercept=  0
    =undefined
    >
    Part 3 will follow soon.
    
About