mode.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "mode.h"
  9. // Implementation
  10. #include <vector>
  11. template <typename T>
  12. IGL_INLINE void igl::mode(
  13. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
  14. const int d,
  15. Eigen::Matrix<T,Eigen::Dynamic,1> & M)
  16. {
  17. assert(d==1 || d==2);
  18. using namespace std;
  19. int m = X.rows();
  20. int n = X.cols();
  21. M.resize((d==1)?n:m,1);
  22. for(int i = 0;i<((d==2)?m:n);i++)
  23. {
  24. vector<int> counts(((d==2)?n:m),0);
  25. for(int j = 0;j<((d==2)?n:m);j++)
  26. {
  27. T v = (d==2)?X(i,j):X(j,i);
  28. for(int k = 0;k<((d==2)?n:m);k++)
  29. {
  30. T u = (d==2)?X(i,k):X(k,i);
  31. if(v == u)
  32. {
  33. counts[k]++;
  34. }
  35. }
  36. }
  37. assert(counts.size() > 0);
  38. int max_count = -1;
  39. int max_count_j = -1;
  40. int j =0;
  41. for(vector<int>::iterator it = counts.begin();it<counts.end();it++)
  42. {
  43. if(max_count < *it)
  44. {
  45. max_count = *it;
  46. max_count_j = j;
  47. }
  48. j++;
  49. }
  50. M(i,0) = (d==2)?X(i,max_count_j):X(max_count_j,i);
  51. }
  52. }
  53. #ifdef IGL_STATIC_LIBRARY
  54. // Explicit template specialization
  55. // generated by autoexplicit.sh
  56. template void igl::mode<double>(Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, int, Eigen::Matrix<double, -1, 1, 0, -1, 1>&);
  57. // generated by autoexplicit.sh
  58. template void igl::mode<int>(Eigen::Matrix<int, -1, -1, 0, -1, -1> const&, int, Eigen::Matrix<int, -1, 1, 0, -1, 1>&);
  59. #endif