Loading...
Searching...
No Matches
Polyfit.h
1//
2// PolyfitEigen.hpp
3// Polyfit
4//
5// Created by Patrick Löber on 23.11.18.
6// Copyright © 2018 Patrick Loeber. All rights reserved.
7//
8// Modified by Beverly Xu on 2.21.24 FIXME: Proper MIT Licensing
9//
10// Use the Eigen library for fitting: http://eigen.tuxfamily.org
11// See https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html for different methods
12
13// TODO: Add function to get derivative coefficients
14
15#include "Eigen/Dense"
16#include <iostream>
17#include <vector>
18
19Eigen::VectorXd polyfit_Eigen(std::vector<double> x, const Eigen::VectorXd &y, int degree)
20{
21 // Construct the Vandermonde matrix using Eigen's Map for vector initialization
22 Eigen::MatrixXd A = Eigen::MatrixXd::NullaryExpr(x.size(), degree + 1, [&x](Eigen::Index i, Eigen::Index j)
23 { return std::pow(x[i], j); });
24 // Solve the least-squares problem
25 return A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(y);
26}
27
33template <typename T>
34std::vector<T> polyDerivatives(std::vector<T> &coefficients)
35{
36 std::vector<T> derivativeCoefficients;
37 for (size_t degree = 0; degree < coefficients.size(); degree++)
38 {
39 derivativeCoefficients.push_back((degree)*coefficients.at(degree)); // for ax^(n), derivative coefficient is
40 // a*n
41 }
42 return derivativeCoefficients;
43}
44
51template <typename T>
52std::vector<T> polyVal(std::vector<T> &coefficients, std::vector<T> &xValues)
53{
54 std::vector<T> yValues;
55 for (T x : xValues)
56 {
57 T y = (T)(0);
58 for (size_t degree = 0; degree < coefficients.size(); degree++)
59 {
60 y += pow(x, degree) * coefficients.at(degree); // y = ax^n + bx^(n-1) + .... + c
61 }
62 yValues.push_back(y);
63 }
64 return yValues;
65}