median.cpp 895 B

1234567891011121314151617181920212223242526272829303132333435
  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. IGL_INLINE bool igl::median(const Eigen::VectorXd & V, double & m)
  13. {
  14. using namespace std;
  15. if(V.size() == 0)
  16. {
  17. return false;
  18. }
  19. vector<double> vV;
  20. matrix_to_list(V,vV);
  21. // http://stackoverflow.com/a/1719155/148668
  22. size_t n = vV.size()/2;
  23. nth_element(vV.begin(),vV.begin()+n,vV.end());
  24. if(vV.size()%2==0)
  25. {
  26. nth_element(vV.begin(),vV.begin()+n-1,vV.end());
  27. m = 0.5*(vV[n]+vV[n-1]);
  28. }else
  29. {
  30. m = vV[n];
  31. }
  32. return true;
  33. }