writeDMAT.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 "writeDMAT.h"
  9. #include "list_to_matrix.h"
  10. #include <Eigen/Core>
  11. #include <cstdio>
  12. template <typename DerivedW>
  13. IGL_INLINE bool igl::writeDMAT(
  14. const std::string file_name,
  15. const Eigen::MatrixBase<DerivedW> & W,
  16. const bool ascii)
  17. {
  18. FILE * fp = fopen(file_name.c_str(),"wb");
  19. if(fp == NULL)
  20. {
  21. fprintf(stderr,"IOError: writeDMAT() could not open %s...",file_name.c_str());
  22. return false;
  23. }
  24. if(ascii)
  25. {
  26. // first line contains number of rows and number of columns
  27. fprintf(fp,"%d %d\n",(int)W.cols(),(int)W.rows());
  28. // Loop over columns slowly
  29. for(int j = 0;j < W.cols();j++)
  30. {
  31. // loop over rows (down columns) quickly
  32. for(int i = 0;i < W.rows();i++)
  33. {
  34. fprintf(fp,"%0.17lg\n",(double)W(i,j));
  35. }
  36. }
  37. }else
  38. {
  39. // write header for ascii
  40. fprintf(fp,"0 0\n");
  41. // first line contains number of rows and number of columns
  42. fprintf(fp,"%d %d\n",(int)W.cols(),(int)W.rows());
  43. // reader assumes the binary part is double precision
  44. Eigen::MatrixXd Wd = W.template cast<double>();
  45. fwrite(Wd.data(),sizeof(double),Wd.size(),fp);
  46. //// Loop over columns slowly
  47. //for(int j = 0;j < W.cols();j++)
  48. //{
  49. // // loop over rows (down columns) quickly
  50. // for(int i = 0;i < W.rows();i++)
  51. // {
  52. // double d = (double)W(i,j);
  53. // fwrite(&d,sizeof(double),1,fp);
  54. // }
  55. //}
  56. }
  57. fclose(fp);
  58. return true;
  59. }
  60. template <typename Scalar>
  61. IGL_INLINE bool igl::writeDMAT(
  62. const std::string file_name,
  63. const std::vector<std::vector<Scalar> > & W,
  64. const bool ascii)
  65. {
  66. Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> mW;
  67. list_to_matrix(W,mW);
  68. return igl::writeDMAT(file_name,mW,ascii);
  69. }
  70. template <typename Scalar>
  71. IGL_INLINE bool igl::writeDMAT(
  72. const std::string file_name,
  73. const std::vector<Scalar > & W,
  74. const bool ascii)
  75. {
  76. Eigen::Matrix<Scalar,Eigen::Dynamic,1> mW;
  77. list_to_matrix(W,mW);
  78. return igl::writeDMAT(file_name,mW,ascii);
  79. }
  80. #ifdef IGL_STATIC_LIBRARY
  81. // Explicit template specialization
  82. // generated by autoexplicit.sh
  83. #endif