list_to_matrix.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. 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. 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. verbose("m = %d\n",m);
  33. if(m == 0)
  34. {
  35. fprintf(stderr,"Error: list_to_matrix() list is empty()\n");
  36. return false;
  37. }
  38. // number of rows
  39. int n = igl::min_size(V);
  40. verbose("min = %d\n",igl::min_size(V));
  41. verbose("max = %d\n",igl::max_size(V));
  42. if(n != igl::max_size(V))
  43. {
  44. fprintf(stderr,"Error: list_to_matrix()"
  45. " list elements are not all the same size\n");
  46. return false;
  47. }
  48. assert(n != -1);
  49. // Resize output
  50. M.resize(m,n);
  51. // Loop over rows
  52. for(int i = 0;i<m;i++)
  53. {
  54. // Loop over cols
  55. for(int j = 0;j<n;j++)
  56. {
  57. M(i,j) = V[i][j];
  58. }
  59. }
  60. return true;
  61. }
  62. #endif