C++ Eigen庫實現(xiàn)最小二乘擬合的示例代碼
更新時間:2023年07月19日 14:24:23 作者:RockWang.
Eigen 是一個線性算術(shù)的 C++ 模板庫,功能強大、快速、優(yōu)雅以及支持多平臺,本文主要為大家介紹了C++利用Eigen庫實現(xiàn)最小二乘擬合的示例代碼,希望對大家有所幫助
前言
入職第二周的任務(wù)是將導(dǎo)師的Python代碼C化,發(fā)現(xiàn)Python中存在Numpy包直接調(diào)用np.polyfit就好了,但是C++不存在需要造輪子。
示例代碼
#include <iostream>
#include <cmath>
#include <vector>
#include <Eigen/QR>
#include "xtensor/xarray.hpp"
void polyfit( const std::vector<double> &t,
const std::vector<double> &v,
std::vector<double> &coeff,
int order
)
{
// Create Matrix Placeholder of size n x k, n= number of datapoints, k = order of polynomial, for exame k = 3 for cubic polynomial
Eigen::MatrixXd T(t.size(), order + 1);
Eigen::VectorXd V = Eigen::VectorXd::Map(&v.front(), v.size());
//std::cout<<"ceshi"<<std::endl;
//std::cout<<V<<std::endl;
Eigen::VectorXd result;
// check to make sure inputs are correct
assert(t.size() == v.size());
assert(t.size() >= order + 1);
// Populate the matrix
for(size_t i = 0 ; i < t.size(); ++i)
{
for(size_t j = 0; j < order + 1; ++j)
{
T(i, j) = pow(t.at(i), j);
}
}
std::cout<<T<<std::endl;
// Solve for linear least square fit
result = T.householderQr().solve(V);
coeff.resize(order+1);
for (int k = 0; k < order+1; k++)
{
coeff[k] = result[k];
}
}
int main()
{
// time value
std::vector<double> time = {-2, 4, 6, 7, 9};
std::vector<double> velocity = {5, 17, 37, 49, 82};
// placeholder for storing polynomial coefficient
std::vector<double> coeff ;
polyfit(time, velocity, coeff, 2);
xt::xarray<double> c = xt::zeros<double>({3});
for(int i = 0; i < coeff.size(); i++)
{
c[i] = coeff[i];
}
std::vector<double> fitted_velocity;
std::cout<< "Printing fitted values" << std::endl;
for(int p = 0; p < time.size(); ++ p)
{
double vfitted = coeff[0] + coeff[1]*time.at(p) + coeff[2]*(pow(time.at(p), 2)) ;
std::cout<< vfitted<<", ";
fitted_velocity.push_back(vfitted);
}
std::cout<<std::endl;
for(int i = 0; i < c.size(); i++)
{
std::cout<<c[i]<<std::endl;
}
std::cout<<std::endl;
return 0;
}
輸出結(jié)果

到此這篇關(guān)于C++ Eigen庫實現(xiàn)最小二乘擬合的示例代碼的文章就介紹到這了,更多相關(guān)C++ Eigen內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++實現(xiàn)學(xué)生考勤信息管理系統(tǒng)
這篇文章主要為大家詳細介紹了C++實現(xiàn)學(xué)生考勤信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-12-12
QT5中使用QRegularExpression代替QRegExp方法代碼
這篇文章主要給大家介紹了關(guān)于QT5中使用QRegularExpression代替QRegExp的相關(guān)資料,正則表達式(regep)是處理字符串和文本的強大工具,驗證regexp可以測試子字符串是否滿足某些條件,例如是整數(shù)或不包含空格,需要的朋友可以參考下2024-04-04
C語言中結(jié)構(gòu)體(struct)的幾種初始化方法
相信大家都知道struct結(jié)構(gòu)體是C語言中非常重要的復(fù)合類型,初始化的方法很多,那么小編下面對這些方法進行總結(jié),便于自己和大家以后查閱,有需要的可以參考借鑒。2016-08-08

