| 1 |
#include <math.h> |
| 2 |
#include "mat.h" |
| 3 |
#include "matrixdefs.h" |
| 4 |
#include "local_proto.h" |
| 5 |
|
| 6 |
#define EPSILON 1.0e-8 |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
int inverse(MATRIX *a, MATRIX *b) |
| 16 |
{ |
| 17 |
int i, j, k, l, ir = 0, ic = 0, nr, nc; |
| 18 |
int ipivot[MAXROWS], itemp[MAXROWS][2]; |
| 19 |
double pivot[MAXROWS], t; |
| 20 |
static MATRIX m; |
| 21 |
|
| 22 |
if (a->nrows == 0) |
| 23 |
return matrix_error("inv: arg1 not defined\n"); |
| 24 |
|
| 25 |
if (a->nrows != a->ncols) |
| 26 |
return matrix_error("inv: matrix not square\n"); |
| 27 |
|
| 28 |
if (isnull(a)) { |
| 29 |
|
| 30 |
return matrix_error( |
| 31 |
"inv: matrix is singular. Check camera definitions!\n"); |
| 32 |
} |
| 33 |
m_copy(&m, a); |
| 34 |
nr = a->nrows; |
| 35 |
nc = a->ncols; |
| 36 |
|
| 37 |
|
| 38 |
for (i = 0; i < nr; i++) |
| 39 |
ipivot[i] = 0; |
| 40 |
|
| 41 |
for (i = 0; i < nr; i++) { |
| 42 |
t = 0.0; |
| 43 |
for (j = 0; j < nr; j++) { |
| 44 |
if (ipivot[j] == 1) |
| 45 |
continue; |
| 46 |
for (k = 0; k < nc; k++) |
| 47 |
switch (ipivot[k] - 1) { |
| 48 |
case 0: |
| 49 |
break; |
| 50 |
case -1: |
| 51 |
if (fabs(t) < fabs(m.x[j][k])) { |
| 52 |
ir = j; |
| 53 |
ic = k; |
| 54 |
t = m.x[j][k]; |
| 55 |
} |
| 56 |
break; |
| 57 |
case 1: |
| 58 |
return matrix_error( |
| 59 |
"inv: matrix is singular. Check camera definitions!\n"); |
| 60 |
break; |
| 61 |
default: |
| 62 |
return matrix_error( |
| 63 |
"inv: matrix is singular. Check camera definitions!\n"); |
| 64 |
break; |
| 65 |
} |
| 66 |
} |
| 67 |
ipivot[ic] += 1; |
| 68 |
if (ipivot[ic] > 1) |
| 69 |
return matrix_error( |
| 70 |
"inv: matrix is singular. Check camera definitions!\n"); |
| 71 |
|
| 72 |
if (ir != ic) |
| 73 |
for (l = 0; l < nc; l++) { |
| 74 |
t = m.x[ir][l]; |
| 75 |
m.x[ir][l] = m.x[ic][l]; |
| 76 |
m.x[ic][l] = t; |
| 77 |
} |
| 78 |
|
| 79 |
itemp[i][0] = ir; |
| 80 |
itemp[i][1] = ic; |
| 81 |
pivot[i] = m.x[ic][ic]; |
| 82 |
|
| 83 |
|
| 84 |
if (fabs(pivot[i]) < EPSILON) |
| 85 |
return matrix_error( |
| 86 |
"inv: matrix is singular. Check camera definitions!\n"); |
| 87 |
|
| 88 |
|
| 89 |
m.x[ic][ic] = 1.0; |
| 90 |
for (j = 0; j < nc; j++) |
| 91 |
m.x[ic][j] /= pivot[i]; |
| 92 |
|
| 93 |
|
| 94 |
for (k = 0; k < nr; k++) |
| 95 |
if (k != ic) { |
| 96 |
t = m.x[k][ic]; |
| 97 |
m.x[k][ic] = 0.0; |
| 98 |
for (l = 0; l < nc; l++) |
| 99 |
m.x[k][l] -= (m.x[ic][l] * t); |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
|
| 104 |
for (i = 0; i < nc; i++) { |
| 105 |
l = nc - i - 1; |
| 106 |
if (itemp[l][0] == itemp[l][1]) |
| 107 |
continue; |
| 108 |
ir = itemp[l][0]; |
| 109 |
ic = itemp[l][1]; |
| 110 |
for (k = 0; k < nr; k++) { |
| 111 |
t = m.x[k][ir]; |
| 112 |
m.x[k][ir] = m.x[k][ic]; |
| 113 |
m.x[k][ic] = t; |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
b->nrows = nr; |
| 118 |
b->ncols = nc; |
| 119 |
m_copy(b, &m); |
| 120 |
return 1; |
| 121 |
} |