计算矩阵向量< vector< double>的列和. >与迭代器? [英] computing column sums of matrix vector<vector<double> > with iterators?
问题描述
在以前的帖子中,具有行均值的列向量-具有std :: accumulate?我问是否有可能,使用STL功能,用于计算矩阵的行均值
In a previous post column vector with row means -- with std::accumulate? I asked if it was possible, using STL functionality, to compute row means of a matrix
vector< vector<double> > data ( rows, vector<double> ( columns ) );
@benjaminlindley的最高答案不仅是我要找的东西,而且是一件很美的事情.永远充满希望,我认为计算列均值会很容易,所以STL等效于
The top answer by @benjaminlindley is not only just what I was looking for, it is a thing of beauty. Forever hopeful I thought it would be as easy to compute column means, so an STL equivalent of
vector<double> colmeans( data[0].size() );
for ( int i=0; i<data.size(); i++ )
for ( int j=0; j<data[i].size(); j++ )
colmeans[j] += data[i][j]/data.size();
平均值不是在每个vector<double>
内部计算的,而是在所有向量的相同索引上计算的:
where the mean is not computed inside each vector<double>
, but across the same index in all the vectors:
colmeans[0] == ( data[0][0] + data[1][0] + ... data[rows][0] ) / rows
colmeans[1] == ( data[0][1] + data[1][1] + ... data[rows][1] ) / rows
colmeans[2] == ( data[0][2] + data[1][2] + ... data[rows][2] ) / rows
...
colmeans[columns] == ( data[0] [columns] +
data[1] [columns] +
...
data[rows][columns] ) / rows
事实是完全不同的-累加不希望对向量的向量进行操作.是否可以通过[]
运算符使用累加?我什至无法提出看起来不正确的中间形式(摆脱for i
或for j
循环).
It turns out to be quite different -- accumulate does not want to work on vectors of vectors. Is it somehow possible using accumulate with the []
operator? I cannot even come up with an intermediate form (to get rid of eather the for i
or for j
loop) which does not seem right.
使用accumulate
和[]
运算符的东西?还是bind
?
Something with accumulate
and the []
operator? Or bind
?
推荐答案
这是我想到的,使用for_each
和transform
:
Here's something I came up with, using for_each
and transform
:
std::vector<std::vector<double>> data { {1,2,3}, {1,2,3}, {1,2,3} };
std::vector<double> colsums( data[0].size() ); // initialize the size
// to number of columns
std::for_each(data.begin(), data.end(),
[&](const std::vector<double>& row)
{
// Use transform overload that takes two input ranges.
// Note that colsums is the second input range as well as the output range.
// We take each element of the row and add it to the corresponding
// element of colsums vector:
std::transform(row.begin(), row.end(), colsums.begin(), colsums.begin(),
[](double d1, double d2) { return d1 + d2; });
});
std::cout << "Column means: ";
std::transform(
colsums.begin(), colsums.end(),
std::ostream_iterator<double>(std::cout, " "),
[&data](double d) { return d / data.size(); });
这篇关于计算矩阵向量< vector< double>的列和. >与迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!