I am writing a program to do some linear algebra calculations on 300 x 300 complex matrices using the eigen library. I have a family of matrices, which can be thought of as a function of some parameter. Since the matrices are large, I think I would need to allocate them dynamically (via heap allocation). My code is as follows:
for (int i = 0; i < 500; ++i) {
Eigen::Matrix<complex<double>, Eigen::Dynamic, Eigen::Dynamic> matrix = compute_matrix(i);
// Doing calculations
}
Instead of allocating a new object dynamically for each iteration of the loop, would it be possible to allocate an Eigen matrix once, and then reuse it for each iteration of the loop?
More context:
I need to diagonalize a large number of 300 x 300 matrices. Each matrix is defined as:
M = x * A + B
where A and B are two other matrices and “x” is a complex variable.
Here is a more detailed description:
std::vector<Eigen::Vector<double>> eigenvalue_vector(1000);
Eigen::SelfAdjointEigenSolver<Matrix<complex<double>, Dynamic, Dynamic>> solver;
for (int i = 0; i < 1000; ++i) {
Matrix<complex<double>, Dynamic, Dynamic> M = x * A + B;
solver.compute(M)
eigenvalue_vector[i] = solver.eigenvalues()
// Time-consuming calculations based on the eigenvalues and eigenvectors
}
I would like this code to be as efficient as possible, since I have to do the same calculation for a large number of 300 x 300 matrices, each one constructed using a different “x”. Later on, I am going to use MPI or OMP to parallelize the for loop. However, I have been wondering if there are some performance tips that are applicable in this case.
15