sablib
Loading...
Searching...
No Matches
diff.h
Go to the documentation of this file.
1
6
7#ifndef __SABLIB_DIFF_H__
8#define __SABLIB_DIFF_H__
9
10#include <Eigen/Eigen>
11
12namespace sablib {
13
17enum class Dir {
20};
21
30template <typename Derived>
31const typename Derived::PlainObject
32Diff(const Eigen::MatrixBase<Derived> & m0, const int n = 1, const Dir dir = Dir::RowWise)
33{
34 typename Derived::PlainObject m = m0;
35 int rows = m.rows(), columns = m.cols();
36
37 if(dir == Dir::ColumnWise){
38 for(int i = 0; i < n ; i++){
39 int col_counts = columns - i - 1;
40 m.leftCols(col_counts) = m.block(0, 1, rows, col_counts) - m.leftCols(col_counts);
41 }
42
43 return m.leftCols(columns - n);
44 }
45 else{
46 for(int i = 0; i < n ; i++){
47 int row_counts = rows - i - 1;
48 m.topRows(row_counts) = m.block(1, 0, row_counts, columns) - m.topRows(row_counts);
49 }
50
51 return m.topRows(rows - n);
52 }
53}
54
63template <typename Derived>
64const typename Derived::PlainObject
65Diff(const Eigen::SparseMatrixBase<Derived> & m0, const int n = 1, const Dir dir = Dir::RowWise)
66{
67 typename Derived::PlainObject m = m0;
68
69 if(dir == Dir::ColumnWise){
70 for(int i = 0; i < n; i++){
71 m = (m.rightCols(m.cols() - 1) - m.leftCols(m.cols() - 1)).eval();
72 }
73 }
74 else{
75 for(int i = 0; i < n; i++){
76 m = (m.bottomRows(m.rows() - 1) - m.topRows(m.rows() - 1)).eval();
77 }
78 }
79
80 return m;
81}
82
83}; // namespace sablib
84
85#endif // __SABLIB_DIFF_H__
Dir
Direction for difference calculation.
Definition diff.h:17
@ ColumnWise
Definition diff.h:19
@ RowWise
Definition diff.h:18
const Derived::PlainObject Diff(const Eigen::MatrixBase< Derived > &m0, const int n=1, const Dir dir=Dir::RowWise)
Calculates the n-th discrete difference along the given axis.
Definition diff.h:32