# [petsc-users] Question on assembling matrix in parallel

Smith, Barry F. bsmith at mcs.anl.gov
Thu Mar 1 11:25:05 CST 2018

```
> On Mar 1, 2018, at 10:56 AM, Edoardo alinovi <edoardo.alinovi at gmail.com> wrote:
>
> Dear Barry,
>
> thank you very much for the help. I will try to define the matrix as global and let you know  if I have some problems. So just to be sure the following procedure is allowed:
>
> - assemble matrix A  with matAssemblyBegin/MatAssemblyEnd  and rhs1
> - solve the system for u= A\rhs1
>
> - assemble rhs2 and do MatDiagonalSet() to obtain  B by changing the main diagonal of A  without redo matAssemblyBegin/MatAssemblyEnd
> - solve the system for v=B\rhs2
>
> -   assemble rhs3 and do like in the previous point to get C
> -   solve the system for w=C\rhs3

Yes

>
> Thanks,
>
> Edoardo
>
> 2018-03-01 17:27 GMT+01:00 Smith, Barry F. <bsmith at mcs.anl.gov>:
>
>
> > On Mar 1, 2018, at 10:24 AM, Edoardo alinovi <edoardo.alinovi at gmail.com> wrote:
> >
> > Dear All,
> >
> > thanks to your suggestions and Petsc, I have finished to program my finite volume code for CFD that runs in parallel and this is great.
> >
> > I am now tryig to improve its performace and I have a question on matrix in MPIAij format.
> >
> > Basically after the discetization, I have one matrix for each velocity component and they are equal except for the diagonal elements which changes because of the boundary conditions. What I am doing now is:
> >
> > - fill each matrix using matSetValues row by row
> > - finalize each matrix assembly with MatAssemblyBegin and MatAssemblyEnd
> >
> > I am wondering if would be possible  to build just one matrix doing MatAssemblyBegin/MatAssemblyEnd  and for the  other two change the diagonal values locally, thus avoiding the parallel communications.
>
>    You can use MatDiagonalSet() to add to or set the diagonal values of the matrix.
>
> >
> > Also can I put a matrix object in a module and make it a global variable?
>
>    You can.
>
> > Can you provide/link me an example? I am using Fortran.
>
>    There may be examples in the master branch of PETSc. It is straightforward. Just do it and if it doesn't work send us email with full bug report.
>
>
> >
> > Thank you very much for your help,
> >
> > Edoardo
> >
> >
>
>

```