dsplib 1.1.0
C++ DSP library for MATLAB-like coding
Loading...
Searching...
No Matches
ma-filter.h
1#pragma once
2
3#include <dsplib/math.h>
4#include <dsplib/array.h>
5
6namespace dsplib {
7
27template<typename T>
29{
30public:
40 explicit MAFilter(int len)
41 : d_{nextpow2(len)}
42 , w_{len}
43 , buf_((1 << (d_ + 1)) - 1, T{0}) {
44 DSPLIB_ASSERT(len >= 1, "window len must be positive");
45 }
46
59 explicit MAFilter(int len, const base_array<T>& init)
60 : MAFilter{len} {
61 DSPLIB_ASSERT(init.size() == w_, "init size mismatch");
62 for (int i = 0; i < w_; i++) {
63 this->process(init[i]);
64 }
65 }
66
74 T process(const T& in) noexcept {
75 if (w_ == 1) {
76 return in;
77 }
78
79 int k = (1 << d_) - 1 + pos_;
80 buf_[k] = in;
81 while (k > 0) {
82 k = (k - 1) >> 1;
83 buf_[k] = buf_[2 * k + 1] + buf_[2 * k + 2];
84 }
85 pos_ = (pos_ + 1) % w_;
86 return buf_[0] / w_;
87 }
88
98 if (w_ == 1) {
99 return in;
100 }
101
102 const int n = in.size();
103 base_array<T> out(n);
104 for (int i = 0; i < n; i++) {
105 out[i] = process(in[i]);
106 }
107 return out;
108 }
109
117 T operator()(const T& x) noexcept {
118 return this->process(x);
119 }
120
129 return this->process(x);
130 }
131
132private:
133 int d_;
134 int w_;
135 std::vector<T> buf_;
136 int pos_{0};
137};
138
143using MAFilterR = MAFilter<real_t>;
144
149using MAFilterC = MAFilter<cmplx_t>;
150
151} // namespace dsplib
Moving Average Filter implementation using binary tree summation.
Definition ma-filter.h:29
MAFilter(int len)
Construct a MAFilter with specified window length.
Definition ma-filter.h:40
T process(const T &in) noexcept
Process single input sample.
Definition ma-filter.h:74
base_array< T > operator()(span_t< T > x) noexcept
Process array of input samples (operator form)
Definition ma-filter.h:128
MAFilter(int len, const base_array< T > &init)
Construct a MAFilter with initial state.
Definition ma-filter.h:59
T operator()(const T &x) noexcept
Process single input sample (operator form)
Definition ma-filter.h:117
base_array< T > process(span_t< T > in) noexcept
Process array of input samples.
Definition ma-filter.h:97
base dsplib array type
Definition array.h:25
Definition span.h:295