Eigen functions crash in the 2nd round of a for loop
I am using some Eigen functions in my code which has a for loop. I have no problem in the first step but I get an error in the second round (j = 1) in the x_eigen.resize(TotalDist); line. Here is the code:
#include "Eigen/Dense"
usingnamespace Eigen;
void avgTemperature() {
int TotalDist = 400;
int TotalTime = 5000;
vector<vector<double>> A(TotalDist, std::vector<double>(TotalDist));
vector<double> b_copy, x;
VectorXd x_eigen; //Eigen format!
MatrixXd A_eigen;
VectorXd b_eigen;
// ...
for (int j = 0; j < TotalTime; j++) {
for (int i = 0; i < (TotalDist - 1); i++) {
A[i + 1][i] = 1;
A[i][i] = 5;
A[i][i + 1] = -1;
}
A[TotalDist - 1][TotalDist - 1] = 15;
b_copy.resize(TotalDist);
for (int i = 0; i < TotalDist; i++) { b_copy[i] = 15.0; }
A_eigen.resize(TotalDist, TotalDist);
for (int i = 0; i < TotalDist; i++) {
A_eigen.row(i) = Map<VectorXd>(A[i].data(), TotalDist);
}
b_eigen.resize(TotalDist);
for (int i = 0; i < TotalDist; i++) {
b_eigen(i) = b_copy[i];
}
x_eigen.resize(TotalDist);
x_eigen = A_eigen.colPivHouseholderQr().solve(b_eigen);
x.resize(TotalDist);
for (int i = 0; i < TotalDist; i++) {
x[i] = x_eigen(i);
}
A_eigen.resize(0, 0);
b_eigen.resize(0);
x_eigen.resize(0);
b_copy.clear();
// ... I am gonna fill the "x_eigen" for each round of the for loop
} // end of the for loop
} // end of the function
Although I have used the x_eigen.resize(0); in the code but in the j = 1, I get an error in the code in the following line:
x_eigen.resize(TotalDist);
I am curious of the allocating and/or reallocating the memory dealing with the x_eigen, where I have no such problem in A_eigen and b_eigen.