Advertisement
cd62131

3x3 matrix determinant cofactor inverse

May 26th, 2019
631
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. #include <math.h>
  2. #include <stdio.h>
  3. #define M 3
  4. static void print_matrix(const double a[][M]) {
  5.   for (int i = 0; i < M; ++i) {
  6.     for (int j = 0; j < M; ++j) { printf("%f\t", a[i][j]); }
  7.     puts("");
  8.   }
  9. }
  10. static double determinant(const double a[][M]) {
  11.   double D = 0.;
  12.   for (int i = 0; i < M; i++) {
  13.     D += a[0][i] * (a[1][(i + 1) % 3] * a[2][(i + 2) % 3] -
  14.                     a[1][(i + 2) % 3] * a[2][(i + 1) % 3]);
  15.   }
  16.   return D;
  17. }
  18. static void cofactor(const double a[][M], double b[][M]) {
  19.   for (int i = 0; i < M; i++) {
  20.     for (int j = 0; j < M; j++) {
  21.       b[i][j] = a[(i + 1) % 3][(j + 1) % 3] * a[(i + 2) % 3][(j + 2) % 3] -
  22.                 a[(i + 1) % 3][(j + 2) % 3] * a[(i + 2) % 3][(j + 1) % 3];
  23.     }
  24.   }
  25. }
  26. static void inverse(const double a[][M], double b[][M]) {
  27.   double det = determinant(a);
  28.   cofactor(a, b);
  29.   for (int i = 0; i < M; ++i) {
  30.     for (int j = 0; j < M; ++j) {
  31.       if (j < i) {
  32.         continue;
  33.       } else if (i == j) {
  34.         b[i][i] /= det;
  35.         continue;
  36.       }
  37.       double t = b[i][j];
  38.       b[i][j] = b[j][i] / det, b[j][i] = t / det;
  39.     }
  40.   }
  41. }
  42. static void multi(const double a[][M], const double b[][M], double c[][M]) {
  43.   for (int i = 0; i < M; ++i) {
  44.     for (int j = 0; j < M; ++j) {
  45.       double s = 0.;
  46.       for (int k = 0; k < M; ++k) { s += a[i][k] * b[k][j]; }
  47.       c[i][j] = s;
  48.     }
  49.   }
  50. }
  51. int main(void) {
  52.   double a[M][M] = {{4.0, 1.0, -5.0}, {3.0, -2.0, 1.0}, {5.0, 3.0, -5.0}};
  53.   printf("A =\n"), print_matrix(a);
  54.   printf("det(A) = %f\n", determinant(a));
  55.   double b[M][M] = {0};
  56.   cofactor(a, b), printf("cofactor(A) =\n"), print_matrix(b);
  57.   inverse(a, b), printf("inverse(A) =\n"), print_matrix(b);
  58.   double c[M][M] = {0};
  59.   multi(a, b, c), printf("check. A * inverse(A) =\n"), print_matrix(c);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement