[petsc-users] Preallocating a matrix with the d_nnz and o_nnz arrays

Patrick Alken patrick.alken at geomag.info
Mon Aug 22 10:56:34 CDT 2022

I am looping through all the non-zero elements of my matrix to count the 
diagonal and off-diagonal terms in order to pre-allocate the matrix. 
However, what is the criteria for knowing if a given element is in the 
diagonal portion or off-diagonal portion? It seems that it will depend 
on row, column, and also processor. I was doing something like this:

MatGetLocalSize(A, &m, &n);

MatGetOwnershipRange(A, &first, &last);

for (i = first; i < last; ++i) {

     for (j = 0; j < N; ++j) {

         if (abs(i - j) < m)

             ++d_nnz[i - first];


             ++o_nnz[i - first];



However, the criteria: abs(i - j) < m is not correct. I think the 
correct criteria will include the processor number also. Does anyone 
know the correct criteria to use?

More information about the petsc-users mailing list