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?

asked Jun 15, 2020 at 18:26
\$\endgroup\$
2
  • \$\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\$ Commented Jun 15, 2020 at 18:54
  • \$\begingroup\$ @MiguelAvila No, it is stored column wise back to back \$\endgroup\$ Commented Jun 15, 2020 at 19:33

1 Answer 1

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.

answered Jun 15, 2020 at 19:06
\$\endgroup\$
1
  • \$\begingroup\$ Thank you, but this does not display the matrix that I mentioned in my question. \$\endgroup\$ Commented Jun 15, 2020 at 19:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.