最小二乘法拟合曲线:4次函数

void myLMS_poly4(const std::vector<double> src_x, const std::vector<double> src_y, int size, std::vector<double>& dst_y)

{

double a, b, c, d, e;


//Mat A = Mat_<double>(5, 5);
//Mat B = Mat_<double>(5, 1);
//Mat C = Mat_<double>(5, 1);


Mat A(5, 5, CV_64F);
Mat B(5, 1, CV_64F);
Mat X(5, 1, CV_64F);


double sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 8);
}
A.at<double>(0, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 7);
}
A.at<double>(0, 1) = A.at<double>(1, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 6);
}
A.at<double>(0, 2) = A.at<double>(1, 1) = A.at<double>(2, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 5);
}
A.at<double>(0, 3) = A.at<double>(1, 2) = A.at<double>(2, 1) = A.at<double>(3, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 4);
}
A.at<double>(0, 4) = A.at<double>(1, 3) = A.at<double>(2, 2) = A.at<double>(3, 1) = A.at<double>(4, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 3);
}
A.at<double>(1, 4) = A.at<double>(2, 3) = A.at<double>(3, 2) = A.at<double>(4, 1) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 2);
}
A.at<double>(2, 4) = A.at<double>(3, 3) = A.at<double>(4, 2) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += src_x[i];
}
A.at<double>(3, 4) = A.at<double>(4, 3) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += 1;
}
A.at<double>(4, 4) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 4) * src_y[i];
}
B.at<double>(0, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 3) * src_y[i];
}
B.at<double>(1, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += pow(src_x[i], 2) * src_y[i];
}
B.at<double>(2, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += src_x[i] * src_y[i];
}
B.at<double>(3, 0) = sum;


sum = 0;
for (size_t i = 0; i < size; ++i)
{
sum += src_y[i];
}
B.at<double>(4, 0) = sum;


//X = A.inv() * B;
solve(A, B, X);// A * X = B


a = X.at<double>(0, 0);
b = X.at<double>(1, 0);
c = X.at<double>(2, 0);
d = X.at<double>(3, 0);
e = X.at<double>(4, 0);


printf("\n%f, %f, %f, %f, %f\n", a, b, c, d, e);


for (size_t i = 0; i < size; ++i)
{
double ret = a * pow(src_x[i], 4) + b * pow(src_x[i], 3) + c * pow(src_x[i], 2) + d * src_x[i] + e;
dst_y.push_back(ret);
}

}
阅读更多
换一批

没有更多推荐了,返回首页