# [petsc-users] MatSetValues for nonzeros of a sparse matrix

Umut Tabak u.tabak at tudelft.nl
Wed Jan 13 09:16:06 CST 2010

```Dear all,

I am reading some FE system matrices from a commercial FE code. I wrote
an interface where I export them in matrix market format. Also I keep
the row and column indices of the non-zero values and as well the
non-zeros values in arrays of proper type.

The question which I could not conclude is that how to use MatSetValues
for sparse matrix assignments, I mean should I keep all the
values(non-zeros also) in my inputs?( There are also some pointers for
block assignments but they work in the same way I guess)

I have tested with the below code. If I supply only the non-zero
diagonal entries, I get the first row set as expected but this did not
seem so practical to me, because to get what I want accomplished I
should keep all the zero entries as well. And I thought that there
should be a far more efficient way to apply this. (Diagonal assignment
is just an example.) I am sorry if this question is too naive :)

Best regards,
Umut

Mat            A;             /* linear system matrix */
PetscErrorCode ierr;
PetscInt       n = 4;
PetscInt       rI=0,cI=0;
PetscViewer    viewer;
PetscInt index;
//
//
// row indices,m column indices,n of Matrix A
const int idxm[] = { 0,1,2,3 };
const int idxn[] = { 0,1,2,3 };
// values in the matrix A, row major order
PetscScalar valuesMat[]={ 1,0,0,0,0,2,0,0,0,0,3,0,0,0,0,4 };
//PetscScalar valuesMat[]={ 1,2,3,4 };
/* should be the 1st call after the declaration and definition
* block
*/
PetscInitialize(&argc,&args,(char *)0,help);
// intermediate assigments are
// set the values of the Matrix A
ierr = MatSetValues(A, n, idxm, n, idxn, valuesMat,INSERT_VALUES);
CHKERRQ(ierr);
// done so the 2nd argument should be
// MAT_FLUSH_ASSEMBLY
ierr =
MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
CHKERRQ(ierr);
ierr =
MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
CHKERRQ(ierr);
ierr =
MatView(A,PETSC_VIEWER_STDOUT_WORLD);
CHKERRQ(ierr);

ierr = PetscFinalize();CHKERRQ(ierr);
return 0;

```