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?
-
\$\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\$sɪʒɪhɪŋ βɪstɦa kxɐll– sɪʒɪhɪŋ βɪstɦa kxɐll2020年06月15日 18:54:58 +00:00Commented Jun 15, 2020 at 18:54
-
\$\begingroup\$ @MiguelAvila No, it is stored column wise back to back \$\endgroup\$P-A– P-A2020年06月15日 19:33:16 +00:00Commented Jun 15, 2020 at 19:33
1 Answer 1
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.
-
\$\begingroup\$ Thank you, but this does not display the matrix that I mentioned in my question. \$\endgroup\$P-A– P-A2020年06月15日 19:45:39 +00:00Commented Jun 15, 2020 at 19:45