read_eigen_from_CSV.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "read_eigen_from_CSV.h"
  9. #include <sstream>
  10. #include <string>
  11. #include <fstream>
  12. #include <iostream>
  13. #include <vector>
  14. template <typename Scalar>
  15. IGL_INLINE bool igl::read_eigen_from_CSV(const std::string str, Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& M)
  16. {
  17. using namespace std;
  18. using namespace igl;
  19. std::vector<std::vector<Scalar> > Mt;
  20. std::ifstream infile(str.c_str());
  21. std::string line;
  22. while (std::getline(infile, line))
  23. {
  24. std::istringstream iss(line);
  25. vector<Scalar> temp;
  26. Scalar a;
  27. while (iss >> a)
  28. temp.push_back(a);
  29. if (temp.size() != 0) // skip empty lines
  30. Mt.push_back(temp);
  31. }
  32. if (Mt.size() != 0)
  33. {
  34. // Verify that it is indeed a matrix
  35. for (unsigned i = 0; i<Mt.size(); ++i)
  36. {
  37. if (Mt[i].size() != Mt[0].size())
  38. {
  39. infile.close();
  40. return false;
  41. }
  42. }
  43. M.resize(Mt.size(),Mt[0].size());
  44. for (unsigned i = 0; i<Mt.size(); ++i)
  45. for (unsigned j = 0; j<Mt[i].size(); ++j)
  46. M(i,j) = Mt[i][j];
  47. // cerr << "TRUE!" << endl;
  48. return true;
  49. }
  50. infile.close();
  51. return false;
  52. }
  53. #ifndef IGL_HEADER_ONLY
  54. // Explicit template specialization
  55. // generated by autoexplicit.sh
  56. #endif