const int N = 20;
    double *Xa = new double[N];
    double *Ya = new double[N];

    for(int i=0; i<N; i++)
    {
         Xa[i] = i;
         Ya[i] = (rand()%10-10);
    }
    // model: y = a1*x1 + a2*x2 + a3
    CvMat *y = cvCreateMat(N, 1, CV_64FC1);
    CvMat *X = cvCreateMat(N, 3, CV_64FC1);
    CvMat *coeff = cvCreateMat(3, 1, CV_64FC1);

    // fill vector y and matrix X
    for (int i=0; i<N; ++i)
    {
        cvmSet(y, i, 0, Ya[i] );
        cvmSet(X, i, 0, 1 );
        cvmSet(X, i, 1, Xa[i] );
        cvmSet(X, i, 2, Xa[i]*Xa[i] );
    }
    
    cvSolve(X, y, coeff, CV_SVD);

    double x[3];
    for(int i=0; i<3; i++)
    {
       x[i] = cvGet2D(coeff,i,0).val[0];
       StatusBar1->Panels->Items[3+i]->Text = x[i];
    }

    Chart4->RemoveAllSeries();
    //draw points
    TPointSeries *theSeries;
    theSeries = new TPointSeries(Chart4);
    theSeries->SeriesColor = clGreen ;
    theSeries->Marks->Style = psDot;

    theSeries->ParentChart = Chart4;
    for(int j=0; j<N; ++j)
    theSeries->AddXY(Xa[j], Ya[j]);

    //Chart1->Canvas->Brush->Style = bsSolid ;
    TLineSeries *theLine;
    theLine = new TLineSeries(Chart4);
    theLine->SeriesColor = clRed;
    //theLine->LinePen->Style = psDashDot;
    //theLine->LinePen->Style = psSolid;
    //theLine->LinePen->Style = psDash;
    //theLine->LinePen->Style = psDot;
    theLine->LinePen->Style = psDashDotDot;
    //theLine->LinePen->Style = ps;
    theLine->ParentChart = Chart4;
    int xe;
    for(int j=-1; j<N; ++j)
    {
       theLine->AddXY(j, x[0]+x[1]*j + x[2]*j*j);
    }
    delete [] Xa;
    delete [] Ya;
    Chart4->SaveToBitmapFile("c:\\polyfit.jpg");

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()