# Print out symmetric matrix from compactly stored array

I have an array of the form (3x3 case as an example)

$$A = [a_{11}, a_{12}, a_{22}, a_{13}, a_{23}, a_{33}]$$

corresponding to the symmetric matrix

$$\begin{pmatrix} a_{11} & a_{12} & a_{13}\\ a_{12} & a_{22} & a_{23} \\ a_{13} & a_{23} & a_{33} \end{pmatrix}$$

I want to print out this very matrix (in general of size NxN) given the array A (in general of length N*(N+1)/2) in a nice way. My approach was

void print__symm_matrix_packed(double* arr, int N){

int idx2 = 0;

for(int i=0; i<N; i++){
printf("(");

int idx1 = i;

for(int j=0; j<N; j++){
if(j < i){
printf("%f ", arr[idx2 + j]);
} else {
printf("%f ", arr[idx1]);
}
idx1 += j+1;
}
idx2 += i+1;
printf(")\n");
}
}


Is there room for some elegant improvement?

• I think you mean $$A = [a_{11}, a_{12}, a_{13}, a_{21}, a_{22}, a_{23}, a_{31}, a_{32}, a_{33}]$$, Am I correct ? Jun 15 '20 at 18:54
• @MiguelAvila No, it is stored column wise back to back
– P-A
Jun 15 '20 at 19:33

I think it the following is a good approach:

//use lowercase on non constant values
void print_symmetric_packed_matrix(double* compact_matrix, int n)
{
const int entries = N*N;
for (int i = 0; i < entries;)
{
//i++ here avoids i != 0 each iteration
printf("%f ", compact_matrix[i++]);
if (i % N == 0) printf("\n");
}
}


I hope it helped you.

• Thank you, but this does not display the matrix that I mentioned in my question.
– P-A
Jun 15 '20 at 19:45