readDMAT.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #ifndef IGL_READDMAT_H
  2. #define IGL_READDMAT_H
  3. // .dmat is a simple ascii matrix file type, defined as follows. The first line
  4. // is always:
  5. // <#columns> <#rows>
  6. // Then the coefficients of the matrix are given separated by whitespace with
  7. // columns running fastest.
  8. //
  9. // Example:
  10. // The matrix m = [1 2 3; 4 5 6];
  11. // corresponds to a .dmat file containing:
  12. // 3 2
  13. // 1 4 2 5 3 6
  14. #include <Eigen/Core>
  15. #include <string>
  16. namespace igl
  17. {
  18. // Read a matrix from an ascii dmat file
  19. //
  20. // Inputs:
  21. // file_name path to .dmat file
  22. // Outputs:
  23. // W eigen matrix containing read-in coefficients
  24. // Returns true on success, false on error
  25. //
  26. inline bool readDMAT(const std::string file_name, Eigen::MatrixXd & W);
  27. }
  28. // Implementation
  29. #include "verbose.h"
  30. #include <cstdio>
  31. inline bool igl::readDMAT(const std::string file_name, Eigen::MatrixXd & W)
  32. {
  33. FILE * fp = fopen(file_name.c_str(),"r");
  34. if(fp == NULL)
  35. {
  36. fprintf(stderr,"IOError: readDMAT() could not open %s...\n",file_name.c_str());
  37. return false;
  38. }
  39. // first line contains number of rows and number of columns
  40. int num_cols, num_rows;
  41. int res = fscanf(fp,"%d %d\n",&num_cols,&num_rows);
  42. if(res != 2)
  43. {
  44. fclose(fp);
  45. fprintf(stderr,"IOError: readDMAT() first row should be [num cols] [num rows]...\n");
  46. return false;
  47. }
  48. // check that number of columns and rows are sane
  49. if(num_cols < 0)
  50. {
  51. fclose(fp);
  52. fprintf(stderr,"IOError: readDMAT() number of columns %d < 0\n",num_cols);
  53. return false;
  54. }
  55. if(num_rows < 0)
  56. {
  57. fclose(fp);
  58. fprintf(stderr,"IOError: readDMAT() number of rows %d < 0\n",num_rows);
  59. return false;
  60. }
  61. // Resize output to fit matrix
  62. W.resize(num_rows,num_cols);
  63. // Loop over columns slowly
  64. for(int j = 0;j < num_cols;j++)
  65. {
  66. // loop over rows (down columns) quickly
  67. for(int i = 0;i < num_rows;i++)
  68. {
  69. if(fscanf(fp," %lg",&W(i,j)) != 1)
  70. {
  71. fclose(fp);
  72. fprintf(
  73. stderr,
  74. "IOError: readDMAT() bad format after reading %d entries\n",
  75. j*num_rows + i);
  76. return false;
  77. }
  78. }
  79. }
  80. fclose(fp);
  81. return true;
  82. }
  83. #endif