Advertisement
STANAANDREY

mult mat

Feb 27th, 2023 (edited)
621
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MEMERR perror(""); exit(-1);
  4.  
  5. double **mkMat(int n, int m) {
  6.   double **arr = calloc(sizeof(double*), n);
  7.   if (arr == NULL) {
  8.     MEMERR
  9.   }
  10.  
  11.   for (int i = 0; i < n; i++) {
  12.     arr[i] = calloc(sizeof(double), m);
  13.     if (arr[i] != NULL) {
  14.       continue;
  15.     }
  16.     while (i--) {
  17.       free(arr[i]);
  18.     }
  19.     free(arr);
  20.     MEMERR
  21.   }
  22.   return arr;
  23. }
  24.  
  25. void printMat(double *const *const arr, int n, int m) {
  26.   for (int i = 0; i < n; i++) {
  27.     for (int j = 0; j < m; j++) {
  28.       printf("%g ", arr[i][j]);
  29.     }
  30.     puts("");
  31.   }
  32. }
  33.  
  34. void freeMat(double **arr, int n) {
  35.   for (int i = 0; i < n; i++) {
  36.     free(arr[i]);
  37.   }
  38.   free(arr);
  39. }
  40.  
  41. void readMat(double **arr, int n, int m) {
  42.   for (int i = 0; i < n; i++) {
  43.     for (int j = 0; j < m; j++) {
  44.       scanf("%lf", &arr[i][j]);
  45.     }
  46.   }
  47. }
  48.  
  49. double **multMat(double **a, double **b, int n, int m, int k) {
  50.   double **res = mkMat(n, k);
  51.   for (int i = 0; i < n; i++) {
  52.     for (int j = 0; j < k; j++) {
  53.       double sum = 0;
  54.       for (int it = 0; it < m; it++) {
  55.         sum += a[i][it] * b[it][j];
  56.       }
  57.       res[i][j] = sum;
  58.     }
  59.   }
  60.  
  61.   return res;
  62. }
  63.  
  64. int main(void) {
  65.   int m, n, p;
  66.   double **a = NULL, **b = NULL, **c = NULL;
  67.   scanf("%d%d%d", &m, &n, &p);
  68.   a = mkMat(m, n);
  69.   b = mkMat(n, p);
  70.   readMat(a, m, n);
  71.   readMat(b, n, p);
  72.   c = multMat(a, b, m, n, p);
  73.  
  74.   printMat(c, m, p);
  75.   freeMat(a, m);
  76.   freeMat(b, n);
  77.   freeMat(c, m);
  78.   return 0;
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement