Login | Register

Info | Home

BioPHP - Regresion curve and correlation coeficient

Original code submitted by joseba
Code bellow is covered by GNU GPL v2 license.

Description

Last change: 2010/10/18 17:04 | Edit description | Recent Changes | Original description
Computes standard curve (y=ax+b) and correlation coefficient (r).

Code

Last change: 2010/10/18 17:04 | Edit Code | Recent Changes | Download | Original code
// $vals_x and $vals_y are arrays
// response is an array with the following estructure
//     $curve["a"]  - the value for a in the curve (y=ax+b)
//     $curve["b"]  - the value for b in the curve (y=ax+b)
//     $curve["r"]  - the correlation coefficient (r)
function stats_regression_correlation ($vals_x,$vals_y){
        if (sizeof($vals_x)!= sizeof($vals_y)){return;}
        $sum_x=0;
        $sum_x2=0;
        $sum_y=0;
        $sum_y2=0;
        $sum_xy=0;
        $n=sizeof($vals_x);
        foreach($vals_x as $key => $val){
                $val_x=$val;
                $val_y=$vals_y[$key];
                $sum_x+=$val_x;
                $sum_x2+=$val_x*$val_x;
                $sum_y+=$val_y;
                $sum_y2+=$val_y*$val_y;
                $sum_xy+=$val_x*$val_y;
                //print "$val_x\t$val_y\n";
        }
        //print "<hr>sum_x\t$sum_x\nsum_y\t$sum_y\nsum_x2\t$sum_x2\nsum_y2\t$sum_y2\nsum_xy\t$sum_xy\n";

        // y=ax+b
        // calculate a
        $curve["a"]=($n*$sum_xy-$sum_x*$sum_y)/($n*$sum_x2-$sum_x*$sum_x);
         // calculate b
        $curve["b"]=($sum_y/$n)-($curve["a"]*$sum_x/$n);
        // calculate regression
        $curve["r"]=($sum_xy-(1/$n)*$sum_x*$sum_y)/((sqrt($sum_x2-(1/$n)*$sum_x*$sum_x)*(sqrt($sum_y2-(1/$n)*$sum_y*$sum_y))));
        return $curve;
}