F.E.I.S/include/eigen_polyfit.hpp

38 lines
1.1 KiB
C++
Raw Normal View History

2023-07-03 01:40:51 +02:00
// Adapted from https://github.com/patLoeber/Polyfit
//
// PolyfitEigen.hpp
// Polyfit
//
// Created by Patrick Löber on 23.11.18.
// Copyright © 2018 Patrick Loeber. All rights reserved.
//
// Use the Eigen library for fitting: http://eigen.tuxfamily.org
// See https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html for different methods
#include "Eigen/Dense"
template<typename T>
std::vector<T> polyfit(const std::vector<T> &yValues, const int degree) {
2023-07-03 01:40:51 +02:00
using namespace Eigen;
int coeffs = degree + 1;
size_t samples = yValues.size();
2023-07-03 01:40:51 +02:00
2023-07-07 11:22:28 +02:00
MatrixXf A(samples, coeffs);
MatrixXf b(samples, 1);
2023-07-03 01:40:51 +02:00
2023-07-07 11:22:28 +02:00
// fill b matrix
// fill A matrix (Vandermonde matrix)
for (size_t row = 0; row < samples; row++) {
for (int col = 0; col < coeffs; col++) {
2023-07-07 11:22:28 +02:00
A(row, col) = std::pow(row, col);
2023-07-03 01:40:51 +02:00
}
2023-07-07 11:22:28 +02:00
b(row) = yValues[row];
2023-07-03 01:40:51 +02:00
}
2023-07-07 11:22:28 +02:00
// Solve Ax = b
2023-07-03 01:40:51 +02:00
VectorXf coefficients;
2023-07-07 11:22:28 +02:00
coefficients = A.householderQr().solve(b);
return std::vector<T>(coefficients.data(), coefficients.data() + coeffs);
2023-07-03 01:40:51 +02:00
}