Preamble
This method is equivalent to the detrend method of Matlab. It requires the commons math jar from Apache.
Download link
http://commons.apache.org/math/index.html
This method is equivalent to the detrend method of Matlab. It requires the commons math jar from Apache.
Download link
http://commons.apache.org/math/index.html
public static double[] detrend(double[] x, double[] y) {
        
        if (x.length != y.length)
            throw new IllegalArgumentException("The x and y data elements needs to be of the same length");
        
        SimpleRegression regression = new SimpleRegression();
        
        for (int i = 0; i < x.length; i++) {
            regression.addData(x[i], y[i]);
        }
        
        double slope = regression.getSlope();
        double intercept = regression.getIntercept();
        
        for (int i = 0; i < x.length; i++) {
            //y -= intercept + slope * x 
            y[i] -= intercept + (x[i] * slope);
        }
        return y;
    }
