Actual source code: ex33.c

petsc-3.7.3 2016-08-01
Report Typos and Errors
  2: static char help[] = "Writes a matrix using the PETSc sparse format. Input arguments are:\n\
  3:    -fout <file> : output file name\n\n";

  5: #include <petscmat.h>

  9: int main(int argc,char **args)
 10: {
 11:   Mat            A;
 12:   Vec            b;
 13:   char           fileout[PETSC_MAX_PATH_LEN];
 14:   PetscInt       i,j,m = 6,n = 6,N = 36,Ii,J;
 16:   PetscScalar    val,v;
 17:   PetscViewer    view;

 19:   PetscInitialize(&argc,&args,(char*)0,help);

 21:   MatCreate(PETSC_COMM_WORLD,&A);
 22:   MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,N,N);
 23:   MatSetFromOptions(A);
 24:   for (i=0; i<m; i++) {
 25:     for (j=0; j<n; j++) {
 26:       v = -1.0;  Ii = j + n*i;
 27:       if (i>0)   {J = Ii - n; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
 28:       if (i<m-1) {J = Ii + n; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
 29:       if (j>0)   {J = Ii - 1; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
 30:       if (j<n-1) {J = Ii + 1; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
 31:       v = 4.0; MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);
 32:     }
 33:   }
 34:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
 35:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);

 37:   VecCreate(PETSC_COMM_WORLD,&b);
 38:   VecSetSizes(b,PETSC_DECIDE,N);
 39:   VecSetFromOptions(b);
 40:   for (i=0; i<N; i++) {
 41:     val  = i + 1;
 42:     VecSetValues(b,1,&i,&val,INSERT_VALUES);
 43:   }
 44:   VecAssemblyBegin(b);
 45:   VecAssemblyEnd(b);

 47:   PetscOptionsGetString(NULL,NULL,"-fout",fileout,PETSC_MAX_PATH_LEN,NULL);
 48:   PetscViewerBinaryOpen(PETSC_COMM_WORLD,fileout,FILE_MODE_WRITE,&view);
 49:   MatView(A,view);
 50:   VecView(b,view);
 51:   PetscViewerDestroy(&view);

 53:   VecDestroy(&b);
 54:   MatDestroy(&A);

 56:   PetscFinalize();
 57:   return 0;
 58: }