Image Interpolation with Geometric Contour Stencils
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros
invmat.c
Go to the documentation of this file.
1 
16 #include <stdio.h>
17 #include "basic.h"
18 
33 int InvertMatrix(double *InverseData, double *AData, int N)
34 {
35  double *c = 0, *d = 0, *Aj, *Ak, *Inversek;
36  double Temp, Scale, Sum;
37  int i, j, k, Success = 0;
38 
39 
40  if(!(c = (double *)Malloc(sizeof(double)*N))
41  || !(d = (double *)Malloc(sizeof(double)*N)))
42  goto Catch;
43 
44  for(k = 0, Ak = AData; k < N - 1; k++, Ak += N)
45  {
46  Scale = 0.0;
47 
48  for(i = k; i < N; i++)
49  if((Temp = fabs(Ak[i])) > Scale)
50  Scale = Temp;
51 
52  if(Scale == 0.0)
53  {
54  ErrorMessage("Singular matrix.\n");
55  goto Catch; /* Singular matrix */
56  }
57 
58  for(i = k; i < N; i++)
59  Ak[i] /= Scale;
60 
61  for(Sum = 0.0, i = k; i < N; i++)
62  Sum += Ak[i]*Ak[i];
63 
64  Temp = (Ak[k] >= 0.0)? sqrt(Sum) : -sqrt(Sum);
65  Ak[k] += Temp;
66  c[k] = Temp*Ak[k];
67  d[k] = -Scale*Temp;
68 
69  for(j = k + 1, Aj = Ak + N; j < N; j++, Aj += N)
70  {
71  for(Scale = 0.0, i = k; i < N; i++)
72  Scale += Ak[i] * Aj[i];
73 
74  Scale /= c[k];
75 
76  for(i = k; i < N; i++)
77  Aj[i] -= Scale*Ak[i];
78  }
79  }
80 
81  d[N-1] = Ak[k];
82 
83  if(d[N-1] == 0.0)
84  {
85  ErrorMessage("Singular matrix.\n");
86  goto Catch; /* Singular matrix */
87  }
88 
89  for(k = 0, Inversek = InverseData; k < N; k++, Inversek += N)
90  {
91  for(i = 0; i < N; i++)
92  Inversek[i] = -AData[k]*AData[i]/c[0];
93 
94  Inversek[k] += 1.0;
95 
96  for(j = 1, Aj = AData + N; j < N-1; j++, Aj += N)
97  {
98  for(Scale = 0.0, i = j; i < N; i++)
99  Scale += Aj[i]*Inversek[i];
100 
101  Scale /= c[j];
102 
103  for(i = j; i < N; i++)
104  Inversek[i] -= Scale*Aj[i];
105  }
106 
107  Inversek[j] /= d[N-1];
108 
109  for(i = N - 2; i >= 0; i--)
110  {
111  for(Sum = 0.0, j = i + 1, Aj = AData + N*(i + 1); j < N; j++, Aj += N)
112  Sum += Aj[i]*Inversek[j];
113 
114  Inversek[i] = (Inversek[i] - Sum)/d[i];
115  }
116  }
117 
118  Success = 1; /* Finished successfully */
119 Catch: /* Clean up */
120  Free(d);
121  Free(c);
122  return Success;
123 }