VectorXd polyfit代码
时间: 2024-05-16 16:16:09 浏览: 12
以下是使用Eigen库实现的多项式拟合(polyfit)的C++代码:
```c++
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
VectorXd polyfit(VectorXd xvals, VectorXd yvals, int degree)
{
int n = xvals.size();
MatrixXd X(n, degree + 1);
for (int j = 0; j <= degree; j++)
{
X.col(j) = xvals.array().pow(j);
}
VectorXd coeffs = X.householderQr().solve(yvals);
return coeffs;
}
int main()
{
VectorXd x(5), y(5);
x << -2, -1, 0, 1, 2;
y << 3, -1, -2, 1, 4;
VectorXd p = polyfit(x, y, 2);
std::cout << "Coefficients: " << p.transpose() << std::endl;
return 0;
}
```
其中,xvals和yvals分别是输入数据的向量,degree是拟合多项式的阶数,返回值为拟合多项式的系数向量。这里使用了Eigen库的矩阵运算和QR分解求解线性方程组。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)