read_eigen_from_CSV.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "read_eigen_from_CSV.h"
  2. #include <sstream>
  3. #include <string>
  4. #include <fstream>
  5. #include <vector>
  6. namespace igl
  7. {
  8. template <typename Scalar>
  9. IGL_INLINE bool read_eigen_from_CSV(const std::string str, Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& M)
  10. {
  11. using namespace std;
  12. using namespace igl;
  13. std::vector<std::vector<Scalar> > Mt;
  14. std::ifstream infile(str.c_str());
  15. std::string line;
  16. while (std::getline(infile, line))
  17. {
  18. std::istringstream iss(line);
  19. vector<Scalar> temp;
  20. Scalar a;
  21. while (iss >> a)
  22. temp.push_back(a);
  23. if (temp.size() != 0) // skip empty lines
  24. Mt.push_back(temp);
  25. }
  26. if (Mt.size() != 0)
  27. {
  28. // Verify that it is indeed a matrix
  29. for (unsigned i = 0; i<Mt.size(); ++i)
  30. {
  31. if (Mt[i].size() != Mt[0].size())
  32. {
  33. infile.close();
  34. return false;
  35. }
  36. }
  37. M.resize(Mt.size(),Mt[0].size());
  38. for (unsigned i = 0; i<Mt.size(); ++i)
  39. for (unsigned j = 0; j<Mt[i].size(); ++j)
  40. M(i,j) = Mt[i][j];
  41. // cerr << "TRUE!" << endl;
  42. return true;
  43. }
  44. infile.close();
  45. return false;
  46. }
  47. }
  48. #ifndef IGL_HEADER_ONLY
  49. // Explicit template specialization
  50. // generated by autoexplicit.sh
  51. #endif