jacobi.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <stdlib.h>
  2. #include <math.h>
  3. #include <grass/gis.h>
  4. #include <grass/gmath.h>
  5. /***************************************************************************/
  6. /* this does not use the Jacobi method, but it should give the same result */
  7. int jacobi(double a[MX][MX], long n, double d[MX], double v[MX][MX])
  8. {
  9. double *aa[MX], *vv[MX], *dd;
  10. int i;
  11. for (i = 0; i < n; i++) {
  12. aa[i] = &a[i + 1][1];
  13. vv[i] = &v[i + 1][1];
  14. }
  15. dd = &d[1];
  16. eigen(aa, vv, dd, n);
  17. return 0;
  18. }
  19. /***************************************************************************/
  20. static int egcmp(const void *pa, const void *pb)
  21. {
  22. const double *a = *(const double *const *)pa;
  23. const double *b = *(const double *const *)pb;
  24. if (*a > *b)
  25. return -1;
  26. if (*a < *b)
  27. return 1;
  28. return 0;
  29. }
  30. int egvorder(double d[MX], double z[MX][MX], long bands)
  31. {
  32. double *buff;
  33. double **tmp;
  34. int i, j;
  35. /* allocate temporary matrix */
  36. buff = (double *)G_malloc(bands * (bands + 1) * sizeof(double));
  37. tmp = (double **)G_malloc(bands * sizeof(double *));
  38. for (i = 0; i < bands; i++)
  39. tmp[i] = &buff[i * (bands + 1)];
  40. /* concatenate (vertically) z and d into tmp */
  41. for (i = 0; i < bands; i++) {
  42. for (j = 0; j < bands; j++)
  43. tmp[i][j + 1] = z[j + 1][i + 1];
  44. tmp[i][0] = d[i + 1];
  45. }
  46. /* sort the combined matrix */
  47. qsort(tmp, bands, sizeof(double *), egcmp);
  48. /* split tmp into z and d */
  49. for (i = 0; i < bands; i++) {
  50. for (j = 0; j < bands; j++)
  51. z[j + 1][i + 1] = tmp[i][j + 1];
  52. d[i + 1] = tmp[i][0];
  53. }
  54. /* free temporary matrix */
  55. G_free(tmp);
  56. G_free(buff);
  57. return 0;
  58. }
  59. /***************************************************************************/
  60. int transpose(double eigmat[MX][MX], long bands)
  61. {
  62. int i, j;
  63. for (i = 1; i <= bands; i++)
  64. for (j = 1; j < i; j++) {
  65. double tmp = eigmat[i][j];
  66. eigmat[i][j] = eigmat[j][i];
  67. eigmat[j][i] = tmp;
  68. }
  69. return 0;
  70. }
  71. /***************************************************************************/