Least-squares line fitting: Difference between revisions

From JSXGraph Wiki
No edit summary
No edit summary
Line 6: Line 6:
<jsxgraph width="600" height="600">
<jsxgraph width="600" height="600">
var brd = JXG.JSXGraph.initBoard('jxgbox',{boundingbox:[-5,5,5,-5], keepaspectratio:true, axis:true});
var brd = JXG.JSXGraph.initBoard('jxgbox',{boundingbox:[-5,5,5,-5], keepaspectratio:true, axis:true});
var i, p = [], angle, xr, yr, delta = 0.1;
var i, j, p = [], angle, xr, yr, delta = 0.1;


// Random points are constructed which lie roughly on a line
// Random points are constructed which lie roughly on a line
Line 20: Line 20:
brd.unsuspendUpdate();
brd.unsuspendUpdate();


var M = [], y = [], MT, B, c, z, n;
var r = [], rbar = [], x = [], y = [], z = [], A = [[0,0,0],[0,0,0],[0,0,0]], n, d;
n = p.length;
n = p.length;
for (i=0;i<n;i++) {
for (i=0;i<n;i++) {
     M.push([p[i].X(), p[i].Y(), 1.0]);
     r.push([1.0, p[i].X(), p[i].Y()]);
     y.push(p[i].X()*p[i].X() + p[i].Y()*p[i].Y());
     d = r[0]*r[0] + r[1]*r[1] + r[2]*r[2];
    r[0] = 1.0 - r[0]/d;
    r[1] /= d;
    r[2] /= d;
}
}
 
for (j=0;j<3;j++) {
    for (i=0,d=0;i<n;i++) {
        d += r[i][j];
    }
    d /= n;
    rbar[j] = d;
    for (i=0;i<n;i++) {
        r[i][j] -= d;
    }
}
for (i=0;i<n;i++) {
    A[0][0] += r[i][0]*r[i][0];
    A[0][1] += r[i][0]*r[i][1];
    A[0][2] += r[i][0]*r[i][2];
    A[1][0] += r[i][1]*r[i][0];
    A[1][1] += r[i][1]*r[i][1];
    A[1][2] += r[i][1]*r[i][2];
    A[2][0] += r[i][2]*r[i][0];
    A[2][1] += r[i][2]*r[i][1];
    A[2][2] += r[i][2]*r[i][2];
}
console.log(A);
/*
// Now, the general linear least-square fitting problem
// Now, the general linear least-square fitting problem
//    min_z || M*z - y||_2^2
//    min_z || M*z - y||_2^2
Line 46: Line 71:
brd.create('circle',[ [xm,ym], r]);  
brd.create('circle',[ [xm,ym], r]);  
//alert([xm,ym,r].toString());
//alert([xm,ym,r].toString());
/*
// Having constructed the points, we can fit a line described  
// Having constructed the points, we can fit a line described  
// by homogeneous coordinates
// by homogeneous coordinates

Revision as of 16:50, 9 November 2010

This little JXSGraph application finds the line - described by homogeneous coordinates [a,b,c] - that minimizes

[math]\displaystyle{ \sum_{i=1}^n (ax_i+by_i+cz_i)^2. }[/math]

Coming soon...