[petsc-users] Incoherent data entries in array from a dense sub matrix

Pierre Jolivet pierre at joliv.et
Fri Feb 7 04:34:36 CST 2025



> On 7 Feb 2025, at 11:05 AM, medane.tchakorom at univ-fcomte.fr wrote:
> 
> 
> Dear all,
> 
> I have been experiencing incoherent data entries from this code below, when printing the array. Maybe I’am doing something wrong.

What is incoherent?
Everything looks OK to me.

Thanks,
Pierre

> ----------------
> 
>     PetscInt nlines = 8; // lines
>    PetscInt ncols = 4;  // columns
>    PetscMPIInt rank;
>    PetscMPIInt size;
> 
>    // Initialize PETSc
>    PetscCall(PetscInitialize(&argc, &args, NULL, NULL));
>    PetscCallMPI(MPI_Comm_rank(MPI_COMM_WORLD, &rank));
>    PetscCallMPI(MPI_Comm_size(MPI_COMM_WORLD, &size));
> 
>    Mat R_full;
>    Mat R_part;
>    PetscInt idx_first_row = 0;
>    PetscInt idx_one_plus_last_row = nlines / 2;
>    PetscCall(MatCreateDense(PETSC_COMM_WORLD, PETSC_DECIDE, PETSC_DECIDE, nlines, ncols, NULL, &R_full));
> 
>    // Get sub matrix
>    PetscCall(MatDenseGetSubMatrix(R_full, idx_first_row, idx_one_plus_last_row, PETSC_DECIDE, PETSC_DECIDE, &R_part));
>    // Add entries to sub matrix
>    MatSetRandom(R_part, NULL);
>    //View sub matrix
>    PetscCall(MatView(R_part, PETSC_VIEWER_STDOUT_WORLD));
> 
>    // Get array from sub matrix and print entries
>    PetscScalar *buffer;
>    PetscCall(MatDenseGetArray(R_part, &buffer));
>    PetscInt idx_end = (nlines/2) * ncols;
> 
>    for (int i = 0; i < idx_end; i++)
>    {
>        PetscPrintf(PETSC_COMM_SELF, "buffer[%d] = %e \n", i, buffer[i]);
>    }
> 
>    //Restore array to sub matrix
>    PetscCall(MatDenseRestoreArray(R_part, &buffer));
>    // Restore sub matrix
>    PetscCall(MatDenseRestoreSubMatrix(R_full, &R_part));
>    // View the initial matrix
>    PetscCall(MatView(R_full, PETSC_VIEWER_STDOUT_WORLD));
> 
>    PetscCall(MatDestroy(&R_full));
> 
>    PetscCall(PetscFinalize());
>    return 0;
> 
> ----------------
> 
> 
> Thanks
> Medane



More information about the petsc-users mailing list