Kratos Multiphysics Forums
Kratos programming issues => C++ => Topic started by: DanielB on January 31, 2017, 08:34:26 AM

Dear all,
I have a given a mediumsized sparse matrix as follows. In the process of factorizing the matrix, I very often need to access and add values to single positions of the matrix (refer to the following code). Now I realize that filling the matrix in such a way becomes very slow the bigger the matrix gets, I guess because I did not specify any sparsity pattern or so. Hence the very general question: What is the most efficient way in Kratos to fill sparse matrices assuming I can not loop just over all lines and columns in a nested form but I need to access entries more or less randomly:
typedef UblasSpace<double, CompressedMatrix, Vector> SparseSpaceType;
typedef typename SparseSpaceType::MatrixType SparseMatrixType;
SparseMatrixType A_Matrix;
A_Matrix.resize(100000,100000);
A_Matrix.clear();
for(int some_itr=0; some_itr<some_big_number; some_itr++)
{
for(int i=0; i<some_rows_of_A_Matrix;i++)
{
for(int j=0; j<some_collums_of_A_Matrix;j++)
{
A_Matrix(i,j) += some_value;
}
}
}
Any advice is appreciated. Thank you very much in advance.
Best regards,
Daniel

Sparse Matrices are very slow in new allocation. So the way to go is to create a correct graph before filling it. This process consists in allocating the memory for nonzeros in each row of the matrix. you can find an example in ConstructMatrixStructure in the BuilderAndSolvers.
So first you should count nonzeros and create your matrix with
SparseMatrixType A_Matrix(100000,100000, number_of_nonzeros);
Then you should add the your entries in ordered way as you were doing.