# PETSc: Blocking matrices using MatCreateSeqBAIJ and MatSetValuesBlocked

I am a little confused with PETSc's documentation for MatSetValuesBlocked. The code below works fine for matrices when I choose small block sizes, but I get errors when using bigger block sizes for the same matrix. The two main questions:

1) What is the right way to use MatSetValuesBlocked?

2) What is the correct way to generate idxn and idxm, global indices for the row and column blocks, respectively. As an example, for a matrix with m=n=20 and block size = 2, are idxn and idxm = {0,1,2,3,4,5,6,7,8,9} ?

Not sure if there's a mistake in any other function, but I'd like to know what I am doing wrong!

Thanks!

    MatCreateSeqBAIJ(PETSC_COMM_SELF,bs,m,n,nnz*2/m,0,&A);
MatSetOption(A,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
PetscInt idxm[(m/bs)] ; //row index of total number of blocks
PetscInt idxn[(m/bs)] ; //column index of total number of blocks

/*Values from the sparsematrix.mtx file */

for (i=0; i<nnz; i++)
{
fscanf(file,"%d %d %le\n",&row,&col,(double*)&val);
values[i] =  val;
}
fclose(file);

/*Constructing idxm */

for(m_index=0; m_index< (m/bs); m_index++) //Number of blocks rowwise
{
idxm[m_index] = m_index; // For the blocks in the first row

} //idxm construction complete

/*Constructing idxn*/

for(b_index = 0; b_index < (n/bs) ; b_index ++) //Each column for each block
{
idxn[b_index] = b_index;

} //idxn construction complete.

/*Errors occur..*/
MatSetValuesBlocked(A,m/bs,idxm,n/bs,idxn, values, INSERT_VALUES);

MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);

PetscOptionsGetString(NULL,"-fout",fileout,PETSC_MAX_PATH_LEN,NULL);
PetscViewerBinaryOpen(PETSC_COMM_WORLD,fileout,FILE_MODE_WRITE,&view);
MatView(A,view);
VecView(b,view);

MatMult(A, b, res); //Actual multiplication

PetscPrintf(PETSC_COMM_SELF,"Matmult completed...\n");
PetscViewerDestroy(&view);
ierr = VecDestroy(&b);CHKERRQ(ierr);
ierr = MatDestroy(&A);CHKERRQ(ierr);
ierr = VecDestroy(&res);CHKERRQ(ierr);
ierr = PetscRandomDestroy(&r);CHKERRQ(ierr);
ierr = PetscFinalize();


MatSetValuesBlocked contributes logically dense blocks. Given the pattern shown above, you should be calling it once per block-row. You're currently calling it as though the arguments were COO format.
• Thanks! I revised the insertion but I am still missing something: for(i=0; i<m/bs; i++) //For each blocked row: { MatSetValuesBlocked(A,2,&idxm[i],n/bs,idxn, &values[i], INSERT_VALUES); }  – i8086 Sep 13 '13 at 21:56
• What is bs, what m, what is n, and how is values packed? – Jed Brown Sep 17 '13 at 5:41