具有行均值的列向量-具有std :: accumulate? [英] column vector with row means -- with std::accumulate?
问题描述
为了尽可能地懒惰,我在矩阵中读为
In an effort to be as lazy as possible I read in a matrix as
vector< vector<double> > data ( rows, vector<double> ( columns ) );
并尝试使用尽可能多的STL好东西.
and try to use as many STL goodies as I can.
接下来我要做的一件事是计算行均值.在C风格的编程中,
One thing I need to do next is to compute the row means. In C-style programming that would be
vector<double> rowmeans( data.size() );
for ( int i=0; i<data.size(); i++ )
for ( int j=0; j<data[i].size(); j++ )
rowmeans[i] += data[i][j]/data[i].size();
在在C ++中,如何使用向量视图和gsl_stats_mean计算整数向量的均值?解释说:对于数字向量,您可以在一行中计算向量均值,而无需在每一步都调用size()运算符:
In In C++, how to compute the mean of a vector of integers using a vector view and gsl_stats_mean? it is explained that for a vector of numbers you can compute a vector mean in one line without calling the size() operator at every step:
double mean = std::accumulate(stl_v.begin(), stl_v.end(), 0.0) / stl_v.size();
是否可以在向量的向量上使用这些迭代器?中间形式是
Is it possible to use these iterators over a vector of vectors? An intermediate form is
vector<double> rowmeans( rows );
for ( int i=0; i<data.size(); i++ )
rowmeans[i] = std::accumulate(data[i].begin(), data[i].end(), 0.0) / data[i].size();
已经有1条线消失了!但是使用STL函数是否也可以摆脱[i]索引? (在顶层,只需收集行平均值即可.)
already 1 line gone! but using STL functions is it possible to get rid of the [i] index as well? (on the top level it's just a matter of collecting the row means).
推荐答案
std::transform(data.begin(), data.end(), rowmeans.begin(),
[](std::vector<double> const& d) {
return std::accumulate(d.begin(), d.end(), 0.0) / d.size();
});
尽管,我的个人风格将涉及一个命名的lambda或函数,因为我会发现更多的自我证明:
Although, my personal style would involve a named lambda or function, because I would find that more self-documenting:
auto Mean = [](std::vector<double> const& d) { return std::accumulate(d.begin(), d.end(), 0.0) / d.size(); };
std::transform(data.begin(), data.end(), rowmeans.begin(), Mean);
这篇关于具有行均值的列向量-具有std :: accumulate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!