mat_min.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #include "verbose.h"
  32. template <typename T>
  33. inline void igl::mat_min(
  34. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
  35. const int dim,
  36. Eigen::Matrix<T,Eigen::Dynamic,1> & Y,
  37. Eigen::Matrix<int,Eigen::Dynamic,1> & I)
  38. {
  39. assert(dim==1||dim==2);
  40. // output size
  41. int n = (dim==1?X.cols():X.rows());
  42. // resize output
  43. Y.resize(n);
  44. I.resize(n);
  45. // loop over dimension opposite of dim
  46. for(int j = 0;j<n;j++)
  47. {
  48. typename Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>::Index PHONY;
  49. typename Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>::Index i;
  50. T m;
  51. if(dim==1)
  52. {
  53. m = X.col(j).minCoeff(&i,&PHONY);
  54. }else
  55. {
  56. m = X.row(j).minCoeff(&PHONY,&i);
  57. }
  58. Y(j) = m;
  59. I(j) = i;
  60. }
  61. }
  62. #endif