Actual source code: ex4.c

petsc-3.7.3 2016-08-01
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,rstart,rend;
 13:   IS             irkeep,ickeep;
 14:   PetscScalar    value = 1.0;
 15:   PetscViewer    sviewer;

 17:   PetscInitialize(&argc,&argv,(char*)0,help);
 18:   PetscViewerPushFormat(PETSC_VIEWER_STDOUT_WORLD,PETSC_VIEWER_ASCII_COMMON);
 19:   PetscViewerPushFormat(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:   MatSetUp(mat);
 25:   MatGetOwnershipRange(mat,&rstart,&rend);
 26:   for (i=rstart; i<rend; i++) {
 27:     value = (PetscReal)i+1; tmp = i % 5;
 28:     MatSetValues(mat,1,&tmp,1,&i,&value,INSERT_VALUES);
 29:   }
 30:   MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
 31:   MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);
 32:   PetscViewerASCIIPrintf(PETSC_VIEWER_STDOUT_WORLD,"Original matrix\n");
 33:   MatView(mat,PETSC_VIEWER_STDOUT_WORLD);

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

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

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