-
Notifications
You must be signed in to change notification settings - Fork 0
/
eigen_csv.hpp
113 lines (73 loc) · 1.93 KB
/
eigen_csv.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#ifndef EIGEN_CSV_H
#define EIGEN_CSV_H
#include <Eigen/Dense>
#include <cfloat>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
namespace EigenCSV {
template <typename T> void write(const Eigen::DenseBase<T>& A,
const std::string& filename) {
using namespace std;
ofstream file;
file.open(filename);
file << setprecision(DBL_DIG);
for (int i = 0; i < A.rows(); i++) {
for (int j = 0; j < A.cols(); j++)
file << A(i,j) << ',';
file << endl;
}
file.close();
}
template <typename T> void write(const Eigen::DenseBase<T>& A,
const std::vector<std::string>& header,
const std::string& filename) {
using namespace std;
ofstream file;
file.open(filename);
for (unsigned int i = 0; i < header.size(); i++)
file << header[i] << ',';
file << endl;
file << setprecision(DBL_DIG);
for (int i = 0; i < A.rows(); i++) {
for (int j = 0; j < A.cols(); j++)
file << A(i,j) << ',';
file << endl;
}
file.close();
}
template <typename T> void read(const std::string& filename,
bool header, bool resize, Eigen::DenseBase<T>& A) {
using namespace std;
ifstream file;
file.open(filename);
string line, cell;
if (header) {
getline(file, line);
}
vector<vector<double>> vals;
while(getline(file, line)) {
stringstream str(line);
vector<double> valr;
while(getline(str, cell, ','))
valr.push_back(stod(cell));
vals.push_back(valr);
}
int rows, cols;
if (resize) {
rows = vals.size();
cols = vals[0].size();
T& B = (T&) A;
B.resize(rows, cols);
} else {
rows = A.rows();
cols = A.cols();
}
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
A(i,j) = vals[i][j];
}
}
#endif