mat_min.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #ifndef IGL_MAT_MIN_H
  2. #define IGL_MAT_MIN_H
  3. #include <Eigen/Dense>
  4. namespace igl
  5. {
  6. // Ideally this becomes a super overloaded function supporting everything
  7. // that matlab's min supports
  8. // Min function for matrices to act like matlab's min function. Specifically
  9. // like [Y,I] = min(X,[],dim);
  10. //
  11. // Templates:
  12. // T should be a eigen matrix primitive type like int or double
  13. // Inputs:
  14. // X m by n matrix
  15. // dim dimension along which to take min
  16. // Outputs:
  17. // Y n-long sparse vector (if dim == 1)
  18. // or
  19. // Y m-long sparse vector (if dim == 2)
  20. // I vector the same size as Y containing the indices along dim of minimum
  21. // entries
  22. //
  23. // See also: mat_max
  24. template <typename T>
  25. inline void mat_min(
  26. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
  27. const int dim,
  28. Eigen::Matrix<T,Eigen::Dynamic,1> & Y,
  29. Eigen::Matrix<int,Eigen::Dynamic,1> & I);
  30. }
  31. // Implementation
  32. #include "verbose.h"
  33. template <typename T>
  34. inline void igl::mat_min(
  35. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
  36. const int dim,
  37. Eigen::Matrix<T,Eigen::Dynamic,1> & Y,
  38. Eigen::Matrix<int,Eigen::Dynamic,1> & I)
  39. {
  40. assert(dim==1||dim==2);
  41. // output size
  42. int n = (dim==1?X.cols():X.rows());
  43. // resize output
  44. Y.resize(n);
  45. I.resize(n);
  46. // loop over dimension opposite of dim
  47. for(int j = 0;j<n;j++)
  48. {
  49. typename Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>::Index PHONY;
  50. typename Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>::Index i;
  51. T m;
  52. if(dim==1)
  53. {
  54. m = X.col(j).minCoeff(&i,&PHONY);
  55. }else
  56. {
  57. m = X.row(j).minCoeff(&PHONY,&i);
  58. }
  59. Y(j) = m;
  60. I(j) = i;
  61. }
  62. }
  63. #endif