I would like to get the weighted_median of an unsorted, variable
length, eigen c++ vectorXf object. It seems i can use the boost
weighted_median function from boost’s statistical accumulators
library to do that efficiently [?].
In essence, i’m trying to do something very similar to what is done
here. I’m not sure boost’s accumulator are the right framework
for this task (if not please advice!), but i’ve not found another
out the shelf implementation of the O(n) weighted median out there.
My question at this point is whether there a way to replace the
“for(int i=0;i<100;i++)” loop below by a more elegant construct?
P.S. i’ve seen this SO question, but it’s not
really clear how to turn the answer there unto an
operation-able solution.
#include <Eigen/Dense>
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/median.hpp>
#include <boost/accumulators/statistics/weighted_median.hpp>
using namespace boost::accumulators;
using namespace Eigen;
int main(){
accumulator_set<float, stats<tag::median > > acc1;
accumulator_set<float, stats<tag::median >,int> acc2;
VectorXi rw=VectorXi::Random(100);
VectorXf rn=VectorXf::Random(100);
rw=rw.cwiseAbs();
for(int i=0;i<100;i++){
acc1(rn(i));
acc2(rn(i),weight=rw(i));
}
std::cout << " Median: " << median(acc1) << std::endl;
std::cout << "Weighted Median: " << median(acc2) << std::endl;
return 0;
}
What you’re trying to do is to use the boost accumulators to accumulate values in a container of some sort. You’ll notice that even passing
std::vector<float>to an accumulator won’t work. Accumulators are simply not meant to be used that way. You can use accumulators to accumulate vector- or matrix-valued values, of course – but that’s not what you’re after here.You can use
std::for_eachto get rid of the explicit loop, and that’s about it:The question you link to is not relevant anymore in the latest release version of Eigen3. The code given there runs just fine and produces correct results.