mode.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #ifndef IGL_MODE_H
  2. #define IGL_MODE_H
  3. #include <Eigen/Dense>
  4. namespace igl
  5. {
  6. // Takes mode of coefficients in a matrix along a given dension
  7. //
  8. // Templates:
  9. // T should be a eigen matrix primitive type like int or double
  10. // Inputs:
  11. // X m by n original matrix
  12. // d dension along which to take mode, m or n
  13. // Outputs:
  14. // M vector containing mode along dension d, if d==1 then this will be a
  15. // n-long vector if d==2 then this will be a m-long vector
  16. template <typename T>
  17. inline void mode(
  18. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
  19. const int d,
  20. Eigen::Matrix<T,Eigen::Dynamic,1> & M);
  21. }
  22. // Implementation
  23. #include <vector>
  24. template <typename T>
  25. inline void igl::mode(
  26. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
  27. const int d,
  28. Eigen::Matrix<T,Eigen::Dynamic,1> & M)
  29. {
  30. assert(d==1 || d==2);
  31. using namespace std;
  32. int m = X.rows();
  33. int n = X.cols();
  34. M.resize((d==1)?n:m,1);
  35. for(int i = 0;i<((d==2)?m:n);i++)
  36. {
  37. vector<int> counts(((d==2)?n:m),0);
  38. for(int j = 0;j<((d==2)?n:m);j++)
  39. {
  40. T v = (d==2)?X(i,j):X(j,i);
  41. for(int k = 0;k<((d==2)?n:m);k++)
  42. {
  43. T u = (d==2)?X(i,k):X(k,i);
  44. if(v == u)
  45. {
  46. counts[k]++;
  47. }
  48. }
  49. }
  50. assert(counts.size() > 0);
  51. int max_count = -1;
  52. int max_count_j = -1;
  53. int j =0;
  54. for(vector<int>::iterator it = counts.begin();it<counts.end();it++)
  55. {
  56. if(max_count < *it)
  57. {
  58. max_count = *it;
  59. max_count_j = j;
  60. }
  61. j++;
  62. }
  63. M(i,0) = (d==2)?X(i,max_count_j):X(max_count_j,i);
  64. }
  65. }
  66. #endif