sablib
Loading...
Searching...
No Matches
polyfit.h
Go to the documentation of this file.
1
6
7#ifndef __SABLIB_POLYFIT_H__
8#define __SABLIB_POLYFIT_H__
9
10#include <stdexcept>
11#include <Eigen/Eigen>
12
13namespace sablib {
14
27template <typename Derived>
28const typename Derived::PlainObject
29PolyFit(const Eigen::MatrixBase<Derived> & x, const Eigen::MatrixBase<Derived> & y, const unsigned int polyorder)
30{
31 using Scalar = typename Derived::PlainObject::Scalar;
32 const int n = x.size();
33 const int m = polyorder + 1;
34
35 if(x.size() != y.size()) {
36 throw std::invalid_argument("PolyFit(): x and y must have the same size.");
37 }
38
39 if(m > n) {
40 throw std::invalid_argument("PolyFit(): polyorder is too high for the number of points.");
41 }
42
43 Eigen::MatrixX<Scalar> A(n, m);
44
45 for(int i = 0; i < n; ++i) {
46 Scalar val = 1.0;
47
48 for(int j = 0; j < m; ++j) {
49 A(i, j) = val;
50 val *= x(i);
51 }
52 }
53
54 return (A.transpose() * A).ldlt().solve(A.transpose() * y);
55}
56
57}; // namespace sablib
58
59#endif // __SABLIB_POLYFIT_H__
const Derived::PlainObject PolyFit(const Eigen::MatrixBase< Derived > &x, const Eigen::MatrixBase< Derived > &y, const unsigned int polyorder)
Fits a polynomial of a specified order to the given data points.
Definition polyfit.h:29