sablib
Loading...
Searching...
No Matches
moving_average.h
Go to the documentation of this file.
1
6
7#ifndef __SABLIB_MOVING_AVERAGE_H__
8#define __SABLIB_MOVING_AVERAGE_H__
9
10#include <cmath>
11#include <stdexcept>
12#include <vector>
13
14#include "../misc/expand.h"
15
16namespace sablib {
17
25const std::vector<double> WeightedMovingAverage(const std::vector<double> & y, const std::vector<double> & w);
26
35template <typename Derived>
36const typename Derived::PlainObject WeightedMovingAverage(
37 const Eigen::MatrixBase<Derived> & y, const Eigen::MatrixBase<Derived> & w
38)
39{
40 // Although parameters are received as MatrixBase<Derived>, only vector classes are allowed.
41 // Others will be rejected at compile time.
42 static_assert(Derived::IsVectorAtCompileTime, "Error: y and w are not vector.");
43
44 if(y.size() == 0 || w.size() == 0) {
45 throw std::invalid_argument("WeightedMovingAverage(): the length of y or w is zero.");
46 }
47
48 using PlainObject = typename Derived::PlainObject;
49
50 int points = w.size();
51 int n = points / 2;
52 PlainObject yy = ExpandBoundaries(y, n);
53 PlainObject result = PlainObject::Zero(y.size());
54
55 if(y.cols() == 1) {
56 for(int i = 0; i < y.size(); i++) {
57 result(i) = (yy.block(i, 0, points, 1).array() * w.array()).matrix().sum();
58 }
59 }
60 else if(y.rows() == 1) {
61 for(int i = 0; i < y.size(); i++) {
62 result(i) = (yy.block(0, i, 1, points).array() * w.array()).matrix().sum();
63 }
64 }
65
66 return result;
67}
68
76const std::vector<double> MovingAverage(const std::vector<double> & y, const unsigned int n);
77
86template <typename Derived>
87const typename Derived::PlainObject MovingAverage(const Eigen::MatrixBase<Derived> & y, const unsigned int n)
88{
89 using PlainObject = typename Derived::PlainObject;
90
91 if(n == 0) {
92 throw std::invalid_argument("MovingAverage(): n is zero.");
93 }
94
95 int points = 2 * n + 1;
96 PlainObject w = PlainObject::Ones(points) / points;
97
98 return WeightedMovingAverage(y, w);
99}
100
101}; // namespace sablib
102
103#endif // __SABLIB_MOVING_AVERAGE_H__
Expands and Trim the boundaries of the data.
const Derived::PlainObject ExpandBoundaries(const Eigen::MatrixBase< Derived > &y, const unsigned int n)
Expands the boundaries of a vector by padding with the first and last elements.
Definition expand.h:23
const std::vector< double > WeightedMovingAverage(const std::vector< double > &y, const std::vector< double > &w)
Calculates the weighted moving average of the input signal (std::vector<double> version).
const std::vector< double > MovingAverage(const std::vector< double > &y, const unsigned int n)
Calculates the simple moving average of the input signal (std::vector<double> version).