mode.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <[email protected]>
  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. int m = X.rows();
  19. int n = X.cols();
  20. M.resize((d==1)?n:m,1);
  21. for(int i = 0;i<((d==2)?m:n);i++)
  22. {
  23. std::vector<int> counts(((d==2)?n:m),0);
  24. for(int j = 0;j<((d==2)?n:m);j++)
  25. {
  26. T v = (d==2)?X(i,j):X(j,i);
  27. for(int k = 0;k<((d==2)?n:m);k++)
  28. {
  29. T u = (d==2)?X(i,k):X(k,i);
  30. if(v == u)
  31. {
  32. counts[k]++;
  33. }
  34. }
  35. }
  36. assert(counts.size() > 0);
  37. int max_count = -1;
  38. int max_count_j = -1;
  39. int j =0;
  40. for(std::vector<int>::iterator it = counts.begin();it<counts.end();it++)
  41. {
  42. if(max_count < *it)
  43. {
  44. max_count = *it;
  45. max_count_j = j;
  46. }
  47. j++;
  48. }
  49. M(i,0) = (d==2)?X(i,max_count_j):X(max_count_j,i);
  50. }
  51. }
  52. #ifdef IGL_STATIC_LIBRARY
  53. // Explicit template instantiation
  54. // generated by autoexplicit.sh
  55. template void igl::mode<double>(Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, int, Eigen::Matrix<double, -1, 1, 0, -1, 1>&);
  56. // generated by autoexplicit.sh
  57. template void igl::mode<int>(Eigen::Matrix<int, -1, -1, 0, -1, -1> const&, int, Eigen::Matrix<int, -1, 1, 0, -1, 1>&);
  58. #endif