x2 - code for transforming indices
- firstly, assigning a 4x4 matrix:
int i, j;
double mat[4][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11},
{12, 13, 14, 15}
};
for(i=0; i<4; i++){
printf("\n");
for(j=0; j<4; j++){
printf("%g ", mat[i][j]);
}
}
- converting the 2D matrix to a 1D array stored in a heap of memory:
double * arr = malloc(16 * sizeof(double));
for(i=0; i<4; i++){
for (j=0; j<4; j++){
k = 4 * i + j;
arr[k] = mat[i][j];
}
}
- the new array can be printed using both the old and the new indices:
/* printing using original indices */
for(i=0; i<4; i++){
printf("\n");
for(j=0; j<4; j++){
k = 4 * i + j;
printf("%g ", arr[k]);
}
}
/* printing using new index*/
for(k=0; k<16; k++){
if((k>0) && (k%4==0)) printf("\n");
printf("%g ", arr[k]);
}