readDMAT.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. verbose("Number of rows: %d\n",num_rows);
  49. verbose("Number of cols: %d\n",num_cols);
  50. // check that number of columns and rows are sane
  51. if(num_cols < 0)
  52. {
  53. fclose(fp);
  54. fprintf(stderr,"IOError: readDMAT() number of columns %d < 0\n",num_cols);
  55. return false;
  56. }
  57. if(num_rows < 0)
  58. {
  59. fclose(fp);
  60. fprintf(stderr,"IOError: readDMAT() number of rows %d < 0\n",num_rows);
  61. return false;
  62. }
  63. // Resize output to fit matrix
  64. W.resize(num_rows,num_cols);
  65. // Loop over columns slowly
  66. for(int j = 0;j < num_cols;j++)
  67. {
  68. // loop over rows (down columns) quickly
  69. for(int i = 0;i < num_rows;i++)
  70. {
  71. if(fscanf(fp," %lg",&W(i,j)) != 1)
  72. {
  73. fclose(fp);
  74. fprintf(
  75. stderr,
  76. "IOError: readDMAT() bad format after reading %d entries\n",
  77. j*num_rows + i);
  78. return false;
  79. }
  80. }
  81. }
  82. fclose(fp);
  83. return true;
  84. }
  85. #endif