user906357 user906357 - 4 months ago 34
C Question

Taking the transpose of a matrix in C with 1D arrays

I have a matrix that is represented by a one dimensional array,

example:

the matrix

0 1 2 3
4 5 6 7
8 9 10 11


the array

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11


now give the dimensions of this matrix and the array I want to find the transpose, i.e.

0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11


I'm working in C and here is my code

#include <stdlib.h>
#include <stdio.h>

void transpose(int *array, int m, int n){
int new_array[12];
for (int i=0; i<m*n; i++) {
new_array[i] = ??;
}
for (int i=0; i<m*n; i++) {
array[i] = new_array[i];
}
}

void print_array(int array[], int size){
for (int i=0; i<size; i++) {
printf("%d\n",array[i]);
}
}

int main(){
int array[12];
for (int i=0; i<12; i++) {
array[i]=i;
}

print_array(array,12);
transpose(array,3,4);
print_array(array,12);

return 0;
}


I've tried a dozen times and failed. Is there a simple way to do this that I have missed?

Answer

Use couple of for loops to make the code easier to follow.

void transpose(int *array, int m, int n){

    int new_array[12];
    for (int i = 0; i < m; ++i )
    {
       for (int j = 0; j < n; ++j )
       {
          // Index in the original matrix.
          int index1 = i*n+j;

          // Index in the transpose matrix.
          int index2 = j*m+i;

          new_array[index2] = array[index1];
       }
    }

    for (int i=0; i<m*n; i++) {
        array[i] = new_array[i];
    }
}
Comments