median.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 "median.h"
  9. #include "matrix_to_list.h"
  10. #include <vector>
  11. #include <algorithm>
  12. template <typename DerivedV, typename mType>
  13. IGL_INLINE bool igl::median(
  14. const Eigen::MatrixBase<DerivedV> & V, mType & m)
  15. {
  16. if(V.size() == 0)
  17. {
  18. return false;
  19. }
  20. std::vector<typename DerivedV::Scalar> vV;
  21. matrix_to_list(V,vV);
  22. // http://stackoverflow.com/a/1719155/148668
  23. size_t n = vV.size()/2;
  24. std::nth_element(vV.begin(),vV.begin()+n,vV.end());
  25. if(vV.size()%2==0)
  26. {
  27. std::nth_element(vV.begin(),vV.begin()+n-1,vV.end());
  28. m = 0.5*(vV[n]+vV[n-1]);
  29. }else
  30. {
  31. m = vV[n];
  32. }
  33. return true;
  34. }
  35. #ifdef IGL_STATIC_LIBRARY
  36. // Explicit template instantiation
  37. // generated by autoexplicit.sh
  38. template bool igl::median<Eigen::Block<Eigen::Matrix<float, -1, -1, 0, -1, -1>, -1, 1, true>, float>(Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<float, -1, -1, 0, -1, -1>, -1, 1, true> > const&, float&);
  39. // generated by autoexplicit.sh
  40. template bool igl::median<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, -1, 1, true>, double>(Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, -1, 1, true> > const&, double&);
  41. template bool igl::median<Eigen::Matrix<double, -1, 1, 0, -1, 1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, double&);
  42. #endif