invert.c 815 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #include <grass/gis.h>
  2. #include <grass/gmath.h>
  3. int invert(
  4. /* inverts a matrix of arbitrary size input as a 2D array. */
  5. double **a, /* input/output matrix */
  6. int n, /* dimension */
  7. double *det, /* determinant */
  8. int *indx, /* indx = G_alloc_ivector(n); */
  9. double **y, /* y = G_alloc_matrix(n,n); */
  10. double *col /* col = G_alloc_vector(n); */
  11. )
  12. {
  13. int i, j;
  14. double d;
  15. if (G_ludcmp(a, n, indx, &d)) {
  16. for (j = 0; j < n; j++) {
  17. d *= a[j][j];
  18. for (i = 0; i < n; i++)
  19. col[i] = 0.0;
  20. col[j] = 1.0;
  21. G_lubksb(a, n, indx, col);
  22. for (i = 0; i < n; i++)
  23. y[i][j] = col[i];
  24. }
  25. *det = d;
  26. for (i = 0; i < n; i++)
  27. for (j = 0; j < n; j++)
  28. a[i][j] = y[i][j];
  29. return (1);
  30. }
  31. else {
  32. *det = 0.0;
  33. return (0);
  34. }
  35. }