MRPT  1.9.9
csv.h
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | https://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file |
6  | See: https://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See: https://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 #pragma once
10 
11 #include <fstream>
12 #include <iosfwd>
13 #include <sstream>
14 #include <string>
15 #include <vector>
16 
17 namespace mrpt::io
18 {
19 /** @defgroup csv_load Load matrix from CSV file (in #include <mrpt/io/csv.h>)
20  * \ingroup mrpt_io_grp
21  * @{ */
22 
23 /** Loads a matrix from a CSV text file.
24  * Empty lines or those with a trailing `#` are ignored.
25  * Requires including the `<Eigen/Dense>` header in the user translation unit.
26  *
27  * \tparam MATRIX Can be any Eigen matrix or mrpt::math matrices.
28  *
29  * \note Based on: https://stackoverflow.com/a/39146048/1631514
30  */
31 template <typename MATRIX>
32 void load_csv(const std::string& path, MATRIX& M)
33 {
34  std::ifstream indata;
35  indata.open(path);
36  std::string line;
37  std::vector<typename MATRIX::Scalar> values;
38  uint rows = 0;
39  while (std::getline(indata, line))
40  {
41  if (!line.empty() && line[0] == '#') continue;
42  std::stringstream lineStream(line);
43  std::string cell;
44  while (std::getline(lineStream, cell, ','))
45  {
46  std::stringstream cs(cell);
47  typename MATRIX::Scalar val;
48  cs >> val;
49  values.push_back(val);
50  }
51  ++rows;
52  }
53  // Convert from RowMajor if needed!
54  M = Eigen::Map<const Eigen::Matrix<
55  typename MATRIX::Scalar, MATRIX::RowsAtCompileTime,
56  MATRIX::ColsAtCompileTime, Eigen::RowMajor>>(
57  values.data(), rows, values.size() / rows);
58 }
59 
60 /** @} */
61 
62 } // namespace mrpt::io
double Scalar
Definition: KmUtils.h:43
int val
Definition: mrpt_jpeglib.h:957
void load_csv(const std::string &path, MATRIX &M)
Loads a matrix from a CSV text file.
Definition: csv.h:32



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: c7a3bec24 Sun Mar 29 18:33:13 2020 +0200 at dom mar 29 18:50:38 CEST 2020