median.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 "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. using namespace std;
  17. if(V.size() == 0)
  18. {
  19. return false;
  20. }
  21. vector<typename DerivedV::Scalar> vV;
  22. matrix_to_list(V,vV);
  23. // http://stackoverflow.com/a/1719155/148668
  24. size_t n = vV.size()/2;
  25. nth_element(vV.begin(),vV.begin()+n,vV.end());
  26. if(vV.size()%2==0)
  27. {
  28. nth_element(vV.begin(),vV.begin()+n-1,vV.end());
  29. m = 0.5*(vV[n]+vV[n-1]);
  30. }else
  31. {
  32. m = vV[n];
  33. }
  34. return true;
  35. }
  36. #ifdef IGL_STATIC_LIBRARY
  37. // Explicit template instantiation
  38. // generated by autoexplicit.sh
  39. 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&);
  40. // generated by autoexplicit.sh
  41. 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&);
  42. #endif