gpt4 book ai didi

c++ - boost++::weighted_median 和 eigen::vectorXf --newbie

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:12:13 25 4
gpt4 key购买 nike

我想得到一个未排序的变量的加权中位数长度, Eigen c++ vectorXf 对象。看来我可以使用 boost来自 boost 统计累加器的 weighted_median 函数库来有效地做到这一点 [?]。

本质上,我正在尝试做一些与已完成的非常相似的事情 here .我不确定 boost 的累加器是正确的框架对于这个任务(如果不请建议!),但我还没有找到另一个O(n) 加权中位数的现成实现。

此时我的问题是是否有办法替换“for(int i=0;i<100;i++)”下面的循环更优雅?

附言我看过this所以问题,但事实并非如此真的很清楚如何将那里的答案变成可操作的解决方案。

#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;
}

最佳答案

您要做的是使用 boost 累加器在某种容器中累加值。您会注意到,即使通过 std::vector<float>到蓄能器是行不通的。蓄能器根本不应该以这种方式使用。当然,您可以使用累加器来累加 vector 值或矩阵值 - 但这不是您想要的。

您可以使用 std::for_each摆脱显式循环,仅此而已:

// median
using boost::bind;
using boost::ref;
std::for_each(rn.data(), rn.data()+rn.rows(), bind<void>( ref(acc1), _1 ) );

question你链接到的在 Eigen3 的最新版本中不再相关。那里给出的代码运行良好并产生正确的结果。

关于c++ - boost++::weighted_median 和 eigen::vectorXf --newbie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11147761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com