Actual source code: ex4.c

petsc-3.6.4 2016-04-12
Report Typos and Errors
  2: static char help[] = "Creates a matrix, inserts some values, and tests MatGetSubMatrices() and MatZeroEntries().\n\n";

  4: #include <petscmat.h>

  8: int main(int argc,char **argv)
  9: {
 10:   Mat            mat,submat,*submatrices;
 11:   PetscInt       m = 10,n = 10,i = 4,tmp;
 13:   IS             irkeep,ickeep;
 14:   PetscScalar    value = 1.0;
 15:   PetscViewer    sviewer;

 17:   PetscInitialize(&argc,&argv,(char*)0,help);
 18:   PetscViewerSetFormat(PETSC_VIEWER_STDOUT_WORLD,PETSC_VIEWER_ASCII_COMMON);
 19:   PetscViewerSetFormat(PETSC_VIEWER_STDOUT_SELF,PETSC_VIEWER_ASCII_COMMON);

 21:   MatCreate(PETSC_COMM_WORLD,&mat);
 22:   MatSetSizes(mat,PETSC_DECIDE,PETSC_DECIDE,m,n);
 23:   MatSetFromOptions(mat);
 24:   for (i=0; i<m; i++) {
 25:     value = (PetscReal)i+1; tmp = i % 5;
 26:     MatSetValues(mat,1,&tmp,1,&i,&value,INSERT_VALUES);
 27:   }
 28:   MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
 29:   MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);
 30:   PetscViewerASCIIPrintf(PETSC_VIEWER_STDOUT_WORLD,"Original matrix\n");
 31:   MatView(mat,PETSC_VIEWER_STDOUT_WORLD);

 33:   /* Form submatrix with rows 2-4 and columns 4-8 */
 34:   ISCreateStride(PETSC_COMM_SELF,3,2,1,&irkeep);
 35:   ISCreateStride(PETSC_COMM_SELF,5,4,1,&ickeep);
 36:   MatGetSubMatrices(mat,1,&irkeep,&ickeep,MAT_INITIAL_MATRIX,&submatrices);
 37:   submat = *submatrices;
 38:   PetscFree(submatrices);
 39:   /*
 40:      sviewer will cause the submatrices (one per processor) to be printed in the correct order
 41:   */
 42:   PetscViewerASCIIPrintf(PETSC_VIEWER_STDOUT_WORLD,"Submatrices\n");
 43:   PetscViewerASCIISynchronizedAllow(PETSC_VIEWER_STDOUT_WORLD,PETSC_TRUE);
 44:   PetscViewerGetSingleton(PETSC_VIEWER_STDOUT_WORLD,&sviewer);
 45:   MatView(submat,sviewer);
 46:   PetscViewerRestoreSingleton(PETSC_VIEWER_STDOUT_WORLD,&sviewer);
 47:   PetscViewerFlush(PETSC_VIEWER_STDOUT_WORLD);

 49:   /* Zero the original matrix */
 50:   PetscViewerASCIIPrintf(PETSC_VIEWER_STDOUT_WORLD,"Original zeroed matrix\n");
 51:   MatZeroEntries(mat);
 52:   MatView(mat,PETSC_VIEWER_STDOUT_WORLD);

 54:   ISDestroy(&irkeep);
 55:   ISDestroy(&ickeep);
 56:   MatDestroy(&submat);
 57:   MatDestroy(&mat);
 58:   PetscFinalize();
 59:   return 0;
 60: }