Sunday, February 1, 2015

Matrix transpose with malloc in C

Kode C berikut adalah cara melakukan Transpose Matrix dengan malloc().

matrixA.txt
1.4    2.9    2.1
3.7    3.1    4.4
8.1    9.7    2.1
3.1    3.1    1.0


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

int main()
{
 float **matrix, **transpose;
 int m, n, i, j;
 m=4;
 n=3;

 matrix = malloc(m * sizeof(float));
 transpose = malloc(n * sizeof(float));

 for (i = 0; i < m; i++)
 {
  matrix[i] = malloc(n * sizeof(float));
 }

 for (i = 0; i < n; i++)
 {
  transpose[i] = malloc(m * sizeof(float));
 }

FILE *inputA=fopen("matrixA.txt","r");
 for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
    fscanf(inputA,"%f",&matrix[i][j]);
        }
    }
  fclose(inputA);



for (i = 0; i < m; i++)
 {
  for (j = 0; j < n; j++)
  {
   transpose[j][i] = matrix[i][j];
  }
 }

//print
for(i=0;i<n;++i)
       {
  for(j=0;j<m;++j)
        {
            printf("%f ",transpose[i][j]);
         }
        printf("\n");
        }

//free mat

for (i = 0; i < m; i++)
 {
  free(matrix[i]);
 }
for (i = 0; i < n; i++)
 {
  free(transpose[i]);
 }
 free(matrix);
 free(transpose);
 return 0;
}




agus@agus-desktop:~/programming$ gcc -o transpose transpose.c
agus@agus-desktop:~/programming$ ./transpose
1.400000 3.700000 8.100000 3.100000
2.900000 3.100000 9.700000 3.100000
2.100000 4.400000 2.100000 1.000000

Untuk mengoutputkannya ke sebuah file:
agus@agus-desktop:~/programming$ ./transpose > hasil.txt

No comments: