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: https://libeigen.gitlab.io
11
12// TODO: Add function to get derivative coefficients
13
14#include "Eigen/Dense"
15#include <iostream>
16#include <vector>
17
18Eigen::VectorXd polyfit_Eigen(std::vector<double> x, const Eigen::VectorXd &y, int degree)
19{
20 // Construct the Vandermonde matrix using Eigen's Map for vector initialization
21 Eigen::MatrixXd A = Eigen::MatrixXd::NullaryExpr(x.size(), degree + 1, [&x](Eigen::Index i, Eigen::Index j)
22 { return std::pow(x[i], j); });
23 // Solve the least-squares problem
24 return A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(y);
25}
26
32template <typename T>
33std::vector<T> polyDerivatives(std::vector<T> &coefficients)
34{
35 std::vector<T> derivativeCoefficients;
36 for (size_t degree = 0; degree < coefficients.size(); degree++)
37 {
38 derivativeCoefficients.push_back((degree)*coefficients.at(degree)); // for ax^(n), derivative coefficient is
39 // a*n
40 }
41 return derivativeCoefficients;
42}
43
50template <typename T>
51std::vector<T> polyVal(std::vector<T> &coefficients, std::vector<T> &xValues)
52{
53 std::vector<T> yValues;
54 for (T x : xValues)
55 {
56 T y = (T)(0);
57 for (size_t degree = 0; degree < coefficients.size(); degree++)
58 {
59 y += pow(x, degree) * coefficients.at(degree); // y = ax^n + bx^(n-1) + .... + c
60 }
61 yValues.push_back(y);
62 }
63 return yValues;
64}