### Author Topic: Filling Sparse Matrices in Kratos  (Read 1479 times)

#### DanielB

• Newbie
• • Posts: 17 ##### Filling Sparse Matrices in Kratos
« on: January 31, 2017, 08:34:26 AM »
Dear all,

I have a given a medium-sized 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:

Code: [Select]
`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;                }        }}`

Best regards,
Daniel
« Last Edit: January 31, 2017, 08:37:27 AM by DanielB »

#### pooyan

• Global Moderator
• Newbie
•     • Posts: 33 ##### Re: Filling Sparse Matrices in Kratos
« Reply #1 on: January 31, 2017, 10:04:15 AM »
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 non-zeros 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

Code: [Select]
`SparseMatrixType A_Matrix(100000,100000, number_of_nonzeros);`

Then you should add the your entries in ordered way as you were doing.