I'm writing up a bunch (~ a dozen) algorithms that iteratively process a vector in the following pattern:
ArrayXd prev;
ArrayXd curr;
prev = some_initial_vector();
for (i = 0; i < N; ++i) {
// do lots of stuff, many lines to compute curr
// use lots of algorithm specific variables initialised above
...
prev = curr;
}
return curr;
I would like to have a way of returning the entire history of the values of curr
as well, as rows in an ArrayXXd
.
I have tried solving this by writing two classes that exhibit a curr
handle, one as an ArrayXd &
the other as a Block<ArrayXXd, 1, -1>
, but that failed as it's not possible to reassign Block
s.
What is a good way of solving this problem? Maybe I could store the Block
s or the ArrayXd
s themselves in a std::vector
and then convert that to an ArrayXXd
at the end.
Edit: Added sample input, output
struct NotAccumulator {
typedef ArrayXd return_type;
ArrayXd curr;
ArrayXd prev;
void record () {}
return_type result() {
return prev;
}
};
struct RowAccumulator {
typedef ArrayXXd return_type;
ArrayXd curr;
ArrayXd prev;
RowAccumulator(const uint N) {
history.reserve(N);
}
void record () {
history.push_back(curr);
}
return_type result () {
uint rows = history.size();
uint cols = history[0].size();
ArrayXXd result_matrix (rows, cols);
for(uint i = 0; i < rows; ++i) {
result_matrix.row(i) = Map<ArrayXd> (history[i].data(), cols);
}
return result_matrix;
}
private:
std::vector<ArrayXd> history;
};
template <typename Accumulator>
typename Accumulator::return_type add_one(const ArrayXd & start, const uint how_many_times, Accumulator & u) {
u.prev = start;
for (uint i = 0; i < how_many_times; ++i) {
u.curr = 1 + u.prev;
u.record();
u.prev = u.curr;
}
return u.result();
}
ArrayXd start (3);
start << 1, 0, -1;
NotAccumulator notAccumulator;
RowAccumulator rowAccumulator (5);
cout << add_one(start, 5, notAccumulator) << endl;
// outputs 6 5 4
cout << add_one(start, 5, rowAccumulator) << endl;
// outputs 2 1 0\n 3 2 1\n ... 6 5 4