Actual source code: ex33.c
petsc-3.8.4 2018-03-24
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>
7: int main(int argc,char **args)
8: {
9: Mat A;
10: Vec b;
11: char fileout[PETSC_MAX_PATH_LEN];
12: PetscInt i,j,m = 6,n = 6,N = 36,Ii,J;
14: PetscScalar val,v;
15: PetscViewer view;
17: PetscInitialize(&argc,&args,(char*)0,help);if (ierr) return ierr;
18: MatCreate(PETSC_COMM_WORLD,&A);
19: MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,N,N);
20: MatSetFromOptions(A);
21: for (i=0; i<m; i++) {
22: for (j=0; j<n; j++) {
23: v = -1.0; Ii = j + n*i;
24: if (i>0) {J = Ii - n; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
25: if (i<m-1) {J = Ii + n; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
26: if (j>0) {J = Ii - 1; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
27: if (j<n-1) {J = Ii + 1; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
28: v = 4.0; MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);
29: }
30: }
31: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
32: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
34: VecCreate(PETSC_COMM_WORLD,&b);
35: VecSetSizes(b,PETSC_DECIDE,N);
36: VecSetFromOptions(b);
37: for (i=0; i<N; i++) {
38: val = i + 1;
39: VecSetValues(b,1,&i,&val,INSERT_VALUES);
40: }
41: VecAssemblyBegin(b);
42: VecAssemblyEnd(b);
44: PetscOptionsGetString(NULL,NULL,"-fout",fileout,PETSC_MAX_PATH_LEN,NULL);
45: PetscViewerBinaryOpen(PETSC_COMM_WORLD,fileout,FILE_MODE_WRITE,&view);
46: MatView(A,view);
47: VecView(b,view);
48: PetscViewerDestroy(&view);
50: VecDestroy(&b);
51: MatDestroy(&A);
53: PetscFinalize();
54: return ierr;
55: }