#include #include #include // Allocate Matrix of Size rows(h) by cols(w) dynamically double ** make_matrix(int h, int w) { int i; double **array2 = (double **)malloc(h * sizeof(double *)); if (array2) { array2[0] = (double *)malloc(h * w * sizeof(double)); if(array2[0]) { for(i = 1; i < h; i++) array2[i] = array2[0] + i * w; return array2; } else { free(array2); } } return NULL; } // Free memory from a matrix created with make_matrix void free_matrix(double ** m) { if (m[0]) { free(m[0]); free(m); } } // Way to convert between row/col and linear index int in2d(int row, int col, int n){ return col + row * n; } void fscan_matrix(FILE * in, double **m, int h, int w) { int i, j; for(i = 0; i < h; ++i) for(j = 0; j < w; ++j) fscanf(in, "%lf", &m[i][j]); return; } void scan_matrix(double **m, int h, int w){ fscan_matrix(stdin, m, h, w); return; } double ** matrix_transpose(double ** m1, int h, int w) { int i, j; double ** mr = make_matrix(w, h); if (mr) { for(i = 0; i < h; ++i) for(j = 0; j < w; ++j) mr[j][i] = m1[i][j]; return mr; } else { return NULL; } } void fprint_matrix(FILE * out, double **m, int h, int w){ int i, j; fprintf(out, "{\n"); for(i = 0; i < h - 1; ++i) { fprintf(out, " {"); for(j = 0; j < w - 1; ++j) fprintf(out, "%g, ", m[i][j]); fprintf(out, "%g},\n", m[i][j]); } fprintf(out, " {"); for(j = 0; j < w - 1; ++j) fprintf(out, "%g, ", m[i][j]); fprintf(out, "%g}\n}\n", m[i][j]); return; } void print_matrix(double **m, int h, int w){ fprint_matrix(stdout, m, h, w); return; } double ** matrix_mult(double **m1, double **m2, int hm1, int wm1, int wm2){ int i, j, k; double sum; double ** mr = make_matrix(hm1, wm2); if (mr) { for(i = 0; i < hm1; ++i) { for(j = 0; j < wm2; ++j) { sum = 0; for(k = 0; k < wm1; ++k) { sum += m1[i][k] * m2[k][j]; } mr[i][j] = sum; } } } return mr; } int main() { //double m[4][3] = { {0, 1, 2}, {2, 3, 4}, {5, 6, 7}, {9, 1, 0}}; int h = 2, w = 3; double ** m = make_matrix(h, w); scan_matrix(m, h, w); print_matrix(m, h, w); double ** mt = matrix_transpose(m, h, w); if (mt) { print_matrix(mt, w, h); double ** mr = matrix_mult(m, mt, h, w, h); if (mr) { print_matrix(mr, h, h); free_matrix(mr); } free_matrix(mt); } free_matrix(m); return 0; }