3
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ 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 ? \$\endgroup\$ – Miguel Avila Jun 15 at 18:54
  • \$\begingroup\$ @MiguelAvila No, it is stored column wise back to back \$\endgroup\$ – P-A Jun 15 at 19:33
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thank you, but this does not display the matrix that I mentioned in my question. \$\endgroup\$ – P-A Jun 15 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.