mat_max.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #ifndef IGL_MAT_MAX_H
  2. #define IGL_MAT_MAX_H
  3. #include <Eigen/Dense>
  4. namespace igl
  5. {
  6. // Ideally this becomes a super overloaded function supporting everything
  7. // that matlab's max supports
  8. // Max function for matrices to act like matlab's max function. Specifically
  9. // like [Y,I] = max(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 max
  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 maximum
  21. // entries
  22. template <typename T>
  23. inline void mat_max(
  24. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
  25. const int dim,
  26. Eigen::Matrix<T,Eigen::Dynamic,1> & Y,
  27. Eigen::Matrix<int,Eigen::Dynamic,1> & I);
  28. }
  29. // Implementation
  30. template <typename T>
  31. inline void igl::mat_max(
  32. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
  33. const int dim,
  34. Eigen::Matrix<T,Eigen::Dynamic,1> & Y,
  35. Eigen::Matrix<int,Eigen::Dynamic,1> & I)
  36. {
  37. assert(dim==1||dim==2);
  38. // output size
  39. int n = (dim==1?X.cols():X.rows());
  40. // resize output
  41. Y.resize(n);
  42. I.resize(n);
  43. // loop over dimension opposite of dim
  44. for(int j = 0;j<n;j++)
  45. {
  46. int PHONY;
  47. int i;
  48. int m;
  49. if(dim==1)
  50. {
  51. m = X.col(j).maxCoeff(&i,&PHONY);
  52. }else
  53. {
  54. m = X.row(j).maxCoeff(&PHONY,&i);
  55. }
  56. Y(j) = m;
  57. I(j) = i;
  58. }
  59. }
  60. #endif