readDMAT.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. fclose(fp);
  37. fprintf(stderr,"IOError: readDMAT() could not open %s...\n",file_name.c_str());
  38. return false;
  39. }
  40. // first line contains number of rows and number of columns
  41. int num_cols, num_rows;
  42. int res = fscanf(fp,"%d %d\n",&num_cols,&num_rows);
  43. if(res != 2)
  44. {
  45. fclose(fp);
  46. fprintf(stderr,"IOError: readDMAT() first row should be [num cols] [num rows]...\n");
  47. return false;
  48. }
  49. verbose("Number of rows: %d\n",num_rows);
  50. verbose("Number of cols: %d\n",num_cols);
  51. // check that number of columns and rows are sane
  52. if(num_cols < 0)
  53. {
  54. fclose(fp);
  55. fprintf(stderr,"IOError: readDMAT() number of columns %d < 0\n",num_cols);
  56. return false;
  57. }
  58. if(num_rows < 0)
  59. {
  60. fclose(fp);
  61. fprintf(stderr,"IOError: readDMAT() number of rows %d < 0\n",num_rows);
  62. return false;
  63. }
  64. // Resize output to fit matrix
  65. W.resize(num_rows,num_cols);
  66. // Loop over columns slowly
  67. for(int j = 0;j < num_cols;j++)
  68. {
  69. // loop over rows (down columns) quickly
  70. for(int i = 0;i < num_rows;i++)
  71. {
  72. if(fscanf(fp," %lg",&W(i,j)) != 1)
  73. {
  74. fclose(fp);
  75. fprintf(
  76. stderr,
  77. "IOError: readDMAT() bad format after reading %d entries\n",
  78. j*num_rows + i);
  79. return false;
  80. }
  81. }
  82. }
  83. fclose(fp);
  84. return true;
  85. }
  86. #endif