I am a novice at PETSC, and I have been trying to write an FVM code for steady heat conduction in 2D using PETSC (square, regular grid, Dirichlet boundaries)

Since the large matrix , say A, will be sparse I declare 5 non-zeros per row and use MatCreateSeqAIJ()

My question is about assembling the entries of the matrix. In each CV, I call MatSetValues()

and add the 5 coefficients into A using local arrays II, JJ and Values_IJ

1) Is this the "right" or "usual" way to do this? I ask because, it seems to me, am assembling by implicitly using a COO type representation of sparsity in my loop while the matrix representation in PETSC is CSR.

2) If not, is there a way to create the local arrays II, JJ and Values_IJ to fit the CSR format of the matrix and then call MatSetValues()?


1 Answer 1


PETSc does not immediately create your sparse matrix representation. So, when you call MatSetValues(), you, usually, place the values in the intermediate cache which will occasionally get "dumped" into the real sparse matrix storage. So, the impact of the order in which you insert matrix elements is limited.

The fact that the cache is used, allows multiple optimizations during the actual creation of the matrix and more flexibility in the assembly process (which you take advantage of). That's why you would call MatAssemblyBegin() and MatAssemblyEnd() before you are able to use your matrix.

So, it is natural to create a matrix the way you describe in PETSc. When in doubt, see the relevant PETSc examples which usually show the best practices.

You also have an option to create three-array CSR yourself and use MatCreateSeqAIJWithArrays().


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.