sablib
Loading...
Searching...
No Matches
convolve.h
Go to the documentation of this file.
1
6
7#ifndef __SABLIB_CONVOLVE_H__
8#define __SABLIB_CONVOLVE_H__
9
10#include <algorithm>
11#include <Eigen/Eigen>
12
13namespace sablib {
14
18enum class ConvolveMode
19{
23};
24
33template <typename Derived1, typename Derived2>
34const typename Derived1::PlainObject
36 const Eigen::MatrixBase<Derived1> & v1,
37 const Eigen::MatrixBase<Derived2> & v2,
39)
40{
41 // Although parameters are received as MatrixBase<Derived>, only vector classes are allowed.
42 // Others will be rejected at compile time.
43 static_assert(Derived1::IsVectorAtCompileTime, "Error: v1 is not vector.");
44 static_assert(Derived2::IsVectorAtCompileTime, "Error: v2 is not vector.");
45
46 int length, start_index, max_size, min_size;
47 typename Derived1::PlainObject result;
48
49 max_size = std::max(v1.size(), v2.size());
50 min_size = std::min(v1.size(), v2.size());
51
52 length = v1.size() + v2.size() - 1;
53 start_index = 0;
54 result = Derived1::PlainObject::Zero(length);
55
56 for(int j = 0; j < v2.size(); j++) {
57 for(int i = 0; i < v1.size(); i++) {
58 result(i + j) += v1(i) * v2(j);
59 }
60 }
61
62 if (mode == ConvolveMode::Valid) {
63 length = max_size - min_size + 1;
64 start_index = min_size - 1;
65 }
66 else if(mode == ConvolveMode::Same) {
67 length = max_size;
68 start_index = (int)(min_size / 2.0 + 0.5) - 1;
69 }
70
71 if(result.rows() == 1) {
72 return result.block(0, start_index, 1, length);
73 }
74 else {
75 return result.block(start_index, 0, length, 1);
76 }
77}
78
79}; // namespace sablib
80
81#endif // __SABLIB_CONVOLVE_H__
const Derived1::PlainObject Convolve(const Eigen::MatrixBase< Derived1 > &v1, const Eigen::MatrixBase< Derived2 > &v2, const ConvolveMode mode=ConvolveMode::Full)
Returns the discrete, linear convolution of two one-dimensional sequences.
Definition convolve.h:35
ConvolveMode
Mode of Convolve() function.
Definition convolve.h:19