list_to_matrix.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef IGL_LIST_TO_MATRIX_H
  2. #define IGL_LIST_TO_MATRIX_H
  3. #include <vector>
  4. namespace igl
  5. {
  6. // Convert a list (std::vector) of row vectors of the same length to a matrix
  7. // Template:
  8. // T type that can be safely cast to type in Mat via '='
  9. // Mat Matrix type, must implement:
  10. // .resize(m,n)
  11. // .row(i) = Row
  12. // Inputs:
  13. // V a m-long list of vectors of size n
  14. // Outputs:
  15. // M an m by n matrix
  16. // Returns true on success, false on errors
  17. template <typename T, class Mat>
  18. inline bool list_to_matrix(const std::vector<std::vector<T > > & V,Mat & M);
  19. }
  20. // Implementation
  21. #include <cassert>
  22. #include <cstdio>
  23. #include "max_size.h"
  24. #include "min_size.h"
  25. #define VERBOSE
  26. #include "verbose.h"
  27. template <typename T, class Mat>
  28. inline bool igl::list_to_matrix(const std::vector<std::vector<T > > & V,Mat & M)
  29. {
  30. // number of columns
  31. int m = V.size();
  32. if(m == 0)
  33. {
  34. fprintf(stderr,"Error: list_to_matrix() list is empty()\n");
  35. return false;
  36. }
  37. // number of rows
  38. int n = igl::min_size(V);
  39. if(n != igl::max_size(V))
  40. {
  41. fprintf(stderr,"Error: list_to_matrix()"
  42. " list elements are not all the same size\n");
  43. return false;
  44. }
  45. assert(n != -1);
  46. // Resize output
  47. M.resize(m,n);
  48. // Loop over rows
  49. for(int i = 0;i<m;i++)
  50. {
  51. // Loop over cols
  52. for(int j = 0;j<n;j++)
  53. {
  54. M(i,j) = V[i][j];
  55. }
  56. }
  57. return true;
  58. }
  59. #endif