PDA

View Full Version : vector of vector and computes



mickey
12th May 2008, 13:29
Hello,
I have a matrix of int (vector of vector); the problem is that I need to compute the mean of each column (the matrix can be 500 x200); so to do this I did:


foreach (iter_column) {
float sum = 0;
iter_line.setFirstLine;
foreach(iter_line) {
sum += iter_line[iter_coulmn]. value;
}
mean = sum / nOfLine;
}
The problem is that I have to do "two for" one inside other; I thought If is better to do something like to tie a vector<coulum> and do:


class Column {
public:
vector<double> _value;
};
vector<Column> col; //to fill col properly
foreach (col) {
int sum = std::accumulate(col.begin(), col.end(), 0);
mean = sum / col.size();
}

Will be the second way better/faster? Any other ways to improve?

wysota
15th May 2008, 12:47
It won't be faster, because std::accumulate will iterate the vector as well... What you can do is to calculate all columns at once and store results in a temporary vector. It won't be much faster though - you have to iterate all columns in all rows ending up with a complexity of O(n x m) anyway. The only benefit you might have is proper use of cpu cache. You could try making things faster by calculating more than one cell at once (by reading/summing all columns in one machine instruction), but you can have overflows then.