C++ Eigen庫實現(xiàn)最小二乘擬合的示例代碼
更新時間:2023年07月19日 14:24:23 作者:RockWang.
Eigen 是一個線性算術的 C++ 模板庫,功能強大、快速、優(yōu)雅以及支持多平臺,本文主要為大家介紹了C++利用Eigen庫實現(xiàn)最小二乘擬合的示例代碼,希望對大家有所幫助
前言
入職第二周的任務是將導師的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; }
輸出結果
到此這篇關于C++ Eigen庫實現(xiàn)最小二乘擬合的示例代碼的文章就介紹到這了,更多相關C++ Eigen內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
QT5中使用QRegularExpression代替QRegExp方法代碼
這篇文章主要給大家介紹了關于QT5中使用QRegularExpression代替QRegExp的相關資料,正則表達式(regep)是處理字符串和文本的強大工具,驗證regexp可以測試子字符串是否滿足某些條件,例如是整數(shù)或不包含空格,需要的朋友可以參考下2024-04-04